<?php
define("MAX_DESC_LENGTH", 128);
define("ORDER_PAY_UPAY_MERID", 9086); // 联动支付商户Id
define("order_takeout_prefix", "T");
define("order_prefix", "O");
define("order_buy_prefix", "B");
define("order_point_prefix", "P");
define("order_deliver_pickup", "pickup");
define("source_member_points", "积分兑换");
define("GROUP_CATEGORY","category");
define("GROUP_TAG","tag");
define("ORDER_NOTICE_STATUS_CHANGE", "订单状态已修改为：");
define("noticie_title_order", "点菜订单");
define("noticie_title_takeout", "外卖订单");
define('property_type_buy_pro', 1);//积分属性类型（购买商品获得积分）
define("notice_format_item_title", "名称             单价 数量 金额
------------------------------
");
define("notice_format_item", "%s %-5.2f %-2.1g %-5.2f\r\n");
define("notice_format_total",
"------------------------------
合  计：%.2f");
define("notice_format_order", "
=============================
联 系 人 ： %s
联系电话 ： %s
桌位/包间： %s
上菜时间 ： %s
备注说明 ： %s");
define("notice_format_taketout", "
=============================
联 系 人 ： %s
联系电话 ： %s
联系地址 ： %s
备注说明 ： %s");
define("TRADE_TYPE_MWEB", "MWEB");
class product {
	public static function getStoreProduct($sid, $type, $userName) {
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);

		$StoreModel = M("store");
		$where["store.id"] = $sid;
		$result = $StoreModel->alias("store")->where($where)->join("wx_store_district dis ON store.districtId = dis.id")
			->join("wx_store_district_category cat ON dis.districtCategoryId=cat.id")
			->join("wx_store_extend_base base ON base.storeId=store.id")
			->field("store.name sName,store.picUrl sPicUrl,cat.typeId,base.onlineOrder,base.onlineTakeout")->find();
		Session::switchCustomer($customerId);
		if ($userName == '') {
			$result["onlineOrder"] = 0;
			$result["onlineTakeout"] = 0;
		} else {
			$result["userName"] = $userName;
		}

		$tagList = product::getStoreTag($sid, $type, $userName);

		Session::switchCustomer(0);
		$StoreCatModel = M("store_product_category");
		$arrCid = $StoreCatModel->where("storeId=$sid AND type='$type'")->field("categoryId")->select();
		Session::switchCustomer($customerId);
		$cids = '';
		if ($arrCid) {
			foreach ($arrCid as $cid) {
				$cids .= $cid["categoryId"] . ',';
			}
			if (count($arrCid) > 0) {
				$cids = substr($cids, 0, strlen($cids) - 1);
			}
		}
		$result["cids"] = $cids;

		if ($tagList) {
			$result["tags"] = $tagList;
			$productList = product::getProductList($sid, $tagList[0]["id"], $result["cids"], $userName, $type);
			if ($productList) {
				$result["products"] = $productList;
			}
		}

		switch ($result["typeId"]) {
			case type_dish:
				$result["type"] = $type;
				$result["sid"] = $sid;
				Output::instance()->module('product', 'product_dishes')->object($result);
				break;
		}
	}
	//获得商城设置的色调
	public function getMallHue(){
		$customerId = Session::$user['customerId'];
		Session::switchCustomer($customerId);
		$MallStoreModel = m('module_mall_store');
		$mallHue = $MallStoreModel->getField("mallHue");
		switch($mallHue){
			case 1:
				$result['mallHue'] = $mallHue;
				$result['mainColor'] = '#3c8bce';
				$result['secondaryColor'] = '';
				$result['fontColor'] = '#ff0000';
				$result['proDetailMainColor'] = '#FE0300';
				break;
		}
		return $result;
	}

	/**
	 * 获取标签中的产品
	 * $sid: store id
	 * $cids: category id
	 */
	public static function getProductByTagId($tplId, $sid, $tagIds, $cids, $type,$mallid,
											 $start = NULL, $limit = NULL, $rootId = NULL, $counts = NULL, $headerpic = NULL, $title=NULL, $moduleType=NULL,$qId=null,$miUId=null,$visitId='',$lastShareUId='') {
		$userName = Session::$user["userName"];
		$customerId = Session::$user['customerId'];
		$userId = Session::$user['userId'];
		Session::switchCustomer(0);
		$mallModel=M("module_mall_share_store");
		$tagModel=M("module_product_tag");
		Session::switchCustomer($customerId);
		$mallInfoModel = M("module_mall_store");
		$userModel = M("user");
		$MallStoreModel = m('module_mall_store');

		$mall=$mallModel->where("mallId=".$mallid." and customerId = ".$customerId)->find();
		$redis = new RedisAPI();
		$mallInfo = $redis->get('cid'.$customerId.'mallid'.$mallid.'mallInfo');
		if($mallInfo){
			$mallInfo = unserialize($mallInfo);
		}else{
			$mallInfo = $mallInfoModel->find();
			$redis->set('cid'.$customerId.'mallid'.$mallid.'mallInfo', serialize($mallInfo), 60*60);
		}

		//Log::write('jie------t5t6-getMallInfo-'.($t6-$t5));
		if(isset($title)){
			$result['title'] = $title;
		}
		if (isset($rootId)) {
			$materialObjNav = self::getMaterialObj($rootId);
			//Log::write('jie------t7t9-getMallInfo-'.($t8-$t7));
			if ($materialObjNav != NULL) {
				$nav = self::getNav($materialObjNav, $customerId, $userName, $rootId);
				$result["header"] = $nav["header"];
				$result["footer"] = $nav["footer"];
				$result["headerTpl"] = $nav["headerTpl"];
				$result["footerTpl"] = $nav["footerTpl"];
			}
		}
		$param = new stdClass();
		$param->qId = $qId;
		$param->miUId = $miUId;
		/*if(self::isEnjoyMiPrice($param)){
			$result['isEnjoyMiPrice']=1;
		}else{
			$result['isEnjoyMiPrice']=0;
		}
		$quanInfo = self::isPartner();
		if(($qid&&$miUid)){
			return true;
		}*/

		$quanInfo = $redis->get('cid'.$customerId.'userId'.$userId.'quanInfo');
		if($quanInfo){
			$quanInfo = unserialize($quanInfo);
		}else{
			$quanInfo = self::isPartner();
			if($userId){
				$redis->set('cid'.$customerId.'userId'.$userId.'quanInfo', serialize($quanInfo), 60*60);
			}
		}

		if(($qId&&$miUId) || ($quanInfo['qId']&&$quanInfo['uId'])){
			$result['isEnjoyMiPrice']=1;
		}else{
			$result['isEnjoyMiPrice']=0;
		}
		//Log::write('jie------t9t10-getMallInfo-'.($t10-$t9));

		$result['quanInfo']= $quanInfo;
		$Guid = new Guid();
		$guid = $Guid->toString();
		$result['guid']=$guid;

		$resMallHue = $redis->get('cid'.$customerId.'mallid'.$mallid.'mallHue');
		if(is_numeric($resMallHue)){
			$mallHue = $resMallHue;
		}else{
			//商城配色
			$mallHue = $MallStoreModel->getField("mallHue");
			$redis->set('cid'.$customerId.'mallid'.$mallid.'mallHue', $mallHue, 24*60*60);
		}
		$mallHueArr = [];
		if($mallHue == 1){
			$mallHueArr['mallHue'] = $mallHue;
			$mallHueArr['mainColor'] = '#3c8bce';
			$mallHueArr['secondaryColor'] = '';
			$mallHueArr['fontColor'] = '#ff0000';
			$mallHueArr['proDetailMainColor'] = '#FE0300';
		}

		$result['mallHue']=$mallHueArr;
		//$result['mallHue']=self::getMallHue();

		//Log::write('jie------t11t12-getMallHue-'.($t12-$t11));
		if ($tplId == 0) {
			$tagInfo = $tagModel->where("id=$tagIds")->find();
			$arr = product::getProductList($sid, $tagIds, $cids, $userName, $type, $start, $limit);
			foreach($arr['productList'] as $key=>$value){
				$picUrl1 = json_decode($value["picUrl1"],true);
				if($picUrl1[1]&&$picUrl1[1]['picUrl']){
					$arr['productList'][$key]['picUrl']=$picUrl1[1]['picUrl'];
				}
			}
			$result["tagInfo"] = $tagInfo;
			$result['mallInfo']=$mallInfo;
			$result["total"] = $arr["total"];
			$result["item"][0] = $arr;
			$result["visitId"]=$visitId;
			$result["lastShareUId"]=$lastShareUId;
			Output::instance()->module("product","product_common_list")->object($result);
		} else {
			Session::switchCustomer(0);
			$TagModel = D("module_product_tag");
			Session::switchCustomer($customerId);
			$arrTag = explode(",", $tagIds);
			$arrCount = explode(",", $counts);
			$arrModuleType = explode(",",$moduleType);
			$unitArr= array();
			foreach($arrTag as $k=>$v){
				if($v != ''){
					//$result["item"][$k]=$arr;如果$mallid !== null,此处会被下面再次查询的数据覆盖,属于重复, jie 1102
					if(!$mallid){
						$showCount= '';
						if(isset($arrCount[$k]) && $arrCount[$k] != ''){
							$showCount = $arrCount[$k];
						}else{
							$showCount = 4;
						}
						if($start == null && $showCount != null) $start = 0;
						$arr = product::getProductList($sid, $v, $cids, $userName, $type, $start, $showCount);
						$result["item"][$k]=$arr;
//					$result["total"] = $arr["total"];
					}

					//获取展示分类标签信息,暂未优化
					$tag = $TagModel->where("id=$v")->find();
					$result['list'][$k]['title'] = $tag['name'];
					$result['list'][$k]['tagId'] = $tag['id'];
					$result['list'][$k]['moduleType'] = $arrModuleType[$k];
				}
				/*if($v != ''){
					$showCount= '';
					if(isset($arrCount[$k]) && $arrCount[$k] != ''){
						$showCount = $arrCount[$k];
					}else{
						$showCount = 4;
					}
					if($start == null && $showCount != null) $start = 0;
					Log::write('jie----000');
					$arr = product::getProductList($sid, $v, $cids, $userName, $type, $start, $showCount);
					$result["item"][$k]=$arr;
//					$result["total"] = $arr["total"];
					//获取规格
					$tag = $TagModel->where("id=$v")->find();
					$result['list'][$k]['title'] = $tag['name'];
					$result['list'][$k]['tagId'] = $tag['id'];
					$result['list'][$k]['moduleType'] = $arrModuleType[$k];
				}*/
			}
			$result["prodetail"]=$unitArr;
			if ($userName == '') {
				$result["showBtn"] = 0;
			} else {
				$result["showBtn"] = 1;
			}
			$result['headerpic'] = $headerpic;
			if($mallid != NULL){
				$material = $redis->get('cId'.$customerId.'mallId'.$mallid);
				if($material){
					$material = unserialize($material);
				}else{
					$material = self::getMaterial($mallid);
					$redis->set('cId'.$customerId.'mallId'.$mallid, serialize($material), 12*60*60);
				}

				$materialObj = simplexml_load_string($material->xml,'SimpleXMLElement', LIBXML_NOCDATA);
				$obj = $materialObj->Modules->item;
				$moduleInfo = array();
				foreach($obj as $k=>$v){
					$moduleType = (string)$v->moduleType;
					switch($moduleType){
						case 'category':
							$temp = array();
							$temp["moduleType"] = 'category';
							$aboutitemList = array();
							foreach( $v->category as $key=>$value){
								$aboutitem = array();
								$aboutitem["catepic"] = (string)$value->catepic;
								$aboutitem["cateurl"] = (string)$value->cateurl;
								$aboutitem["catetitle"] = (string)$value->catetitle;
								array_push($aboutitemList,$aboutitem);
							}
							$temp["aboutitem"] = $aboutitemList;
							array_push($moduleInfo,$temp);
							break;
						case 'center':
							$temp = array();
							$temp["moduleType"] = 'center';
							foreach($v->center as $key=>$value){
								$temp["aboutitem"]["centerpic"] = (string)$value->centerpic;
								$temp["aboutitem"]["centerlink"] = (string)$value->centerlink;
							}
							array_push($moduleInfo,$temp);
							break;
						case 'topmallinfo':
							$temp = array();
							$temp["moduleType"] = 'topmallinfo';
							$aboutitemList = array();
							foreach($v->topmallinfo as $key=>$value){
								$aboutitem = array();
								$aboutitem["title"] = (string)$value->title;
								array_push($aboutitemList,$aboutitem);
							}
							$temp["aboutitem"] = $aboutitemList;
							array_push($moduleInfo,$temp);
							break;
						case 'pershow':
							$temp = array();
							$temp["moduleType"] = 'pershow';
							$temp["title"]=(string)$v->title;
							$aboutitemList = array();
							foreach($v->pershow as $key=>$value){
								$aboutitem = array();
								$aboutitem["picurl"] = (string)$value->picurl;
								$aboutitem["piclink"] = (string)$value->piclink;
								array_push($aboutitemList,$aboutitem);
							}
							$temp["aboutitem"] = $aboutitemList;
							array_push($moduleInfo,$temp);
							break;
						case 'permenu':
							$temp = array();
							$temp["moduleType"] = 'permenu';
							$aboutitemList = array();
							$temp["permenubg"]=(string)$v->permenubg;
							foreach($v->permenu as $key=>$value){
								$aboutitem = array();
								$aboutitem["name"] = (string)$value->name;
								$aboutitem["link"] = (string)$value->link;
								array_push($aboutitemList,$aboutitem);
							}
							$temp["aboutitem"] = $aboutitemList;
							array_push($moduleInfo,$temp);
							break;
						case 'contentShow':
							$temp=array();
							$temp["moduleType"] = 'contentShow';
							foreach($v->contentShow as $key=>$value){
								$tagId=(int)$value->id;
								$tagnum = (int)$value->tagnum;
								$arr = R("WebPage/getContentCount",array($tagId,$tagnum,true));
								$temp["list"] = $arr;
							}
							array_push($moduleInfo,$temp);
							break;
						case 'tabmenu':
							$temp = array();
							$temp["moduleType"] = 'tabmenu';
							$aboutitemList = array();
							foreach($v->tabmenu as $key=>$value){
								$tagId=(int)$value->tagid;
								$tagnum = (int)$value->tagnum;
								$aboutitem = array();
								$aboutitem["type"] = (string)$value->type;
								$aboutitem["tagnum"] = $tagnum;
								$aboutitem["moreurl"] = (string)$value->moreurl;
								$aboutitem["tagimgurl"] = (string)$value->tagimgurl;
								switch((string)$value->type){
									case 'product':
										$arr = product::getProductList($sid, $tagId, $cids, $userName, $type, 0,$tagnum);
										$tagInfo=R("Product/getTagById", array($tagId,true));
										$aboutitem["showtype"] = (string)$value->showtype;
										break;
									case 'content':
										$arr = R("WebPage/getContentCount",array($tagId,$tagnum,true));
										$tagInfo =R("WebPage/miGetTagById",array($tagId,true));
										break;
								}
								$aboutitem["taginfo"] = $tagInfo;
								$aboutitem["list"] = $arr;
								array_push($aboutitemList,$aboutitem);
							}
							$temp["aboutitem"] = $aboutitemList;
							array_push($moduleInfo,$temp);
							break;
						case 'play':
							$temp = array();
							$temp["moduleType"] = 'play';
							$aboutitemList = array();
							foreach($v->play as $key=>$value){
								$aboutitem = array();
								$aboutitem["picurl"] = (string)$value->picurl;
								$aboutitem["piclink"] = (string)$value->piclink;
								array_push($aboutitemList,$aboutitem);
							}
							$temp["aboutitem"] = $aboutitemList;
							array_push($moduleInfo,$temp);
							break;
						case 'bottomlink':
							$temp = array();
							$temp["moduleType"] = 'bottomlink';
							$aboutitemList = array();
							foreach($v->bottomlink as $key=>$value){
								$aboutitem = array();
								$aboutitem["title"] = (string)$value->title;
								$aboutitem["link"] = (string)$value->link;
								array_push($aboutitemList,$aboutitem);
							}
							$temp["aboutitem"] = $aboutitemList;
							array_push($moduleInfo,$temp);
							break;
						case 'bottomlist':
							$temp = array();
							$temp["moduleType"] = 'bottomlist';
							$aboutitemList = array();
							foreach($v->bottomlist as $key=>$value){
								$aboutitem = array();
								$aboutitem["title"] = (string)$value->title;
								$aboutitem["link"] = (string)$value->link;
								$aboutitem["picurl"] = (string)$value->picurl;
								array_push($aboutitemList,$aboutitem);
							}
							$temp["aboutitem"] = $aboutitemList;
							array_push($moduleInfo,$temp);
							break;
						case 'bottomdeclare':
							$temp = array();
							$temp["moduleType"] = 'bottomdeclare';
							foreach($v->bottomdeclare as $key=>$value){
								$temp["aboutitem"]["title"] = (string)$value->title;
								$temp["aboutitem"]["link"] = (string)$value->link;
							}
							array_push($moduleInfo,$temp);
							break;
						case 'proPlay':
							$tagIds=(int)$v->id;
							$showCount=(int)$v->tagnum;
							$showCount= $showCount ? $showCount : 4;
							if($start == null && $showCount != null) $start = 0;
							$tag = $TagModel->where("id=$tagIds")->find();
							$arr = product::getProductList($sid, $tagIds, $cids, $userName, $type, $start, $showCount);
							$tagInfo=R("Product/getTagById", array($tagIds,true));
							$item = array();
							$item["moduleType"] = $moduleType;
							$item["title"] = $tag['name'];
							$item["tagId"] = $tagIds;
							$item["tagInfo"] = $tagInfo;
							$item["productList"] = $arr['productList'];
							$item["total"] = $arr["total"];
							array_push($moduleInfo,$item);
							break;
						case "screenMode":
							$showsort=(String)$v->showsort;
							$tagGroup=(String)$v->tags;
							$limit=(int)$v->limit;
							$tags = $redis->get('cid'.$customerId.'mallid'.$mallid.'groupId');
							if($tags){
								$tags = unserialize($tags);
							}else{
								$tags = product::getTagsByGroupId($tagGroup);
								$redis->set('cid'.$customerId.'mallid'.$mallid.'groupId', serialize($tags), 12*60*60);
							}
							//Log::write('jie------t23t24-getTagsByGroupId-'.($t24-$t23));
//							!$tagids?$tagids=$tags:'';
//							$arr = product::getProductList($sid, $tagids, $cids, $userName, $type,0,$limit,$orderBy);
							$item = array();
							$item["moduleType"] = $moduleType;
							$item["showsort"] = $showsort;
							$item["tagids"] = $tags;
							$item["limit"] = $limit;
							$item['screen'] = product::getAllTagsByGroupId($tagGroup);
							//Log::write('jie------t25t26-getAllTagsByGroupId-'.($t26-$t25));
//							$item["total"] = ceil($arr["total"]/$limit);
//							$item["productList"] = $arr['productList'];
							array_push($moduleInfo,$item);
							break;
						case "searchBar":
							$item = array();
							$item["moduleType"] = $moduleType;
							array_push($moduleInfo,$item);
							break;
						default :
							$tagIds=(int)$v->id;
							$showCount=(int)$v->tagnum;
							$showCount= $showCount ? $showCount : 4;
							if($start == null && $showCount != null) $start = 0;
							$tag = $TagModel->where("id=$tagIds")->find();
							$arr = product::getProductList($sid, $tagIds, $cids, $userName, $type, $start, $showCount);
							$item = array();
							$item["moduleType"] = $moduleType;
							$item["title"] = $tag['name'];
							$item["tagId"] = $tagIds;
							$item["productList"] = $arr['productList'];
							$item["total"] = $arr["total"];
							array_push($moduleInfo,$item);
							break;
					}
					$arrUnit=self::getProductUnit($arr['productList']);
					$unitArr=array_merge($unitArr,$arrUnit);
				}
			}

			//Log::write('jie------t19t20-getMaterial-'.($t20-$t19));
			$personInfo = $redis->get('cid'.$customerId.'userId'.$userId.'userInfo');
			if($personInfo){
				$personInfo = unserialize($personInfo);
			}else{
				$personInfo = $userModel->alias("a")
					->join("inner join wx_".$customerId."_user_weixin_info b on a.userName = b.openid")
					->field("a.status,b.headimgurl,b.nickname")
					->where("a.userName = '".$userName."'")
					->find();
				if($userId){
					$redis->set('cid'.$customerId.'userId'.$userId.'userInfo', serialize($personInfo), 60*60);
				}
			}


			$personInfo["subscribe"]=0;
			if(!$mallInfo['wechaturl']||$personInfo["status"]=='subscribe'||$personInfo["status"]=='scansubscribe'||!isMicroMessengerUserAgent()){
				$personInfo["subscribe"]=1;
			}
			$result["item"] = $moduleInfo;
			//Log::write('jie------result2'.print_r($result["item"], true));
			$result["mall"]=$mall;
			$result["mallInfo"]=$mallInfo;
			$result["selfInfo"] = $personInfo;
			$prodetail=json_encode($unitArr);
			$result["prodetail"]=$prodetail;
			$result["visitId"]=$visitId;
			$result["lastShareUId"]=$lastShareUId;
			if ($tplId == 1) {
				Output::instance()->module('product', 'product_common_list')->object($result);
			} else if ($tplId == 2) {
				Output::instance()->module('product', 'product_single_list_selected')->object($result);
			}  else if ($tplId == 4) {
				$result["tagId"] = $tagIds;
				Output::instance()->module('product', 'product_multi_list')->object($result);
			} else if ($tplId == 5) {
				$result["tagId"] = $tagIds;
				Output::instance()->module('product', 'product_multi_list_3column')->object($result);
			} else if ($tplId == 6) {
				Output::instance()->module('product', 'product_ychz_index')->object($result);
			}else if ($tplId == 7) {
				Output::instance()->module('product', 'product_yxds_index')->object($result);
			}else if($tplId == 8){
				Output::instance()->module('product', 'product_common_xllist')->object($result);
			}else if($tplId == 9){
				Output::instance()->module('product', 'product_common_bklist')->object($result);
			}else if($tplId == 10){
				Output::instance()->module('product','product_common_list_time')->object($result);
			}
		}
	}
	//获得一级标签下的二级标签结合
	private static function getTagsByGroupId($ids){
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$TagModel = M("module_product_tag");
		Session::switchCustomer($customerId);
		$tags = $TagModel->where("groupId in ($ids)")->field("GROUP_CONCAT(id) as ids")->find();
		return $tags['ids'];
	}
	//获得筛选条件
	private static function getAllTagsByGroupId($ids){
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$TagGroupModel = M("module_product_tag_group");
		$TagModel = M("module_product_tag");
		Session::switchCustomer($customerId);
		$list = $TagGroupModel->where("id in ($ids) and deleted=0")->field("id,groupName")->select();
		$ids = explode(",",$ids);
		$tagList = [];
		foreach($ids as $i=>$id){
			foreach($list as $j=>$item){
				if($item['id']==$id){
					$tagList[] = $item;
				}
			}
		}
		foreach($tagList as $key=>$value){
			$tagList[$key]['list'] = $TagModel->where("groupId=".$value['id'])->field("id,name")->select();
		}
		return $tagList;
	}
	private static function getMaterial($id) {
		$MaterialModel = M("Material");
		$where["id"] = $id;
		$where["module"] = "mall";
		$where["deleted"] = 0;
		$material = $MaterialModel->where($where)->find();
		if (!$material) {
			Output::instance()->resultCode(code_mall_not_exist);
			return;
		}
		$material = (object)$material;
		return $material;
	}

	/*
	 * 获取所有产品标签名，及第一个标签对应产品
	* $cids: category id
	*/
	public static function getProductTagWithPdt($tplId, $tags, $start, $limit, $rootId, $counts) {
		$userName = Session::$user['userName'];
		$customerId = Session::$user['customerId'];
		$ProductTagModel = M("module_product_tag");
		$arrCondition = array();
		$arrTag = explode(",", $tags);
		$arrCount = explode(",",$counts);

		$arr = array();
		foreach ($arrTag as $k=>$tag) {
			if($tag!=''){
				$where['tag.id'] = array('eq',$tag);
				$tmp = $ProductTagModel->alias("tag")->where($where)->field("tag.*")->distinct("tag.id")->order("number asc")
					->join("wx_module_product_tag_list list ON tag.id = list.tagId")
					->join("wx_module_product pdt ON list.pid = pdt.id")->find();

				$tmp['count'] = $arrCount[$k];
				array_push($arr,$tmp);
			}
		}
		if (!$arr) {
			Output::instance()->resultCode(code_success);
			return;
		}

		$TagListModel = M("module_product_tag_list");
		for($i = 0; $i < count($arr); $i++) {
			$tagId = $arr[$i]["id"];
			$conditionTag["tag.tagId"] = $tagId;
			$conditionTag["detail.oid"] = 0;
			$conditionTag["detail.fromUserName"] = $userName;
			$conditionTag["detail.type"] = type_buy;
			$reserveCount = $TagListModel->alias("tag")->where($conditionTag)
				->join("wx_module_product_order_detail detail ON detail.pid=tag.pid")->count("tag.tagId");
			// 			echo $TagListModel->getLastSql() . '</br>';
			$arr[$i]["reserveCount"] = $reserveCount;
		}

		if ($arr) {
			$result["tags"] = $arr;
			$productList = product::getProductList(-1, $arr[0]["id"], '', $userName, type_buy, $start, $limit);
			if ($productList) {
				$result["products"] = $productList;
			}
		}
		if ($userName == '') {
			$result["showBtn"] = 0;
		} else {
			$result["showBtn"] = 1;
		}
		// 页面中区别当前显示类别组产品还是标签组产品
		$result["groupBy"] = GROUP_TAG;
		switch ($tplId) {
			case 4:
				Output::instance()->module('product', 'product_multi_list')->object($result);
				break;
			case 5:
				Output::instance()->module('product', 'product_multi_list_3column')->object($result);
				break;
		}
	}

	public static function updateOrderDetail($param) {
		$token=$param->token;
		$token = Module::callModule("personCenter",null,"verifyToken",$token);
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$userName = Session::$user['userName'];
		$customerId = Session::$user['customerId'];
		$userId = Session::$user['userId'];
		Session::switchCustomer(0);
		$ProductModel = D('module_product');
		$productSpc = M("module_product_specification");
		$DetailModel = M("module_product_order_detail");
		$sid=$param->sid;
		$oid=$param->oid;
		$pid=$param->pid;
		$size=$param->size;
		$color=$param->color;
		$type=$param->type;
		$did=$param->did;
		$count=$param->count;
		$deposit=$param->deposit;
		$map["fromUserName"] = array('eq',$userName);
		$map["userId"] = array('eq',$userId);
		$map['_logic'] = "OR";
		$conditionDetail["_complex"] = $map;
		$conditionDetail["oid"] = $oid;
		$conditionDetail["pid"] = $pid;
		$conditionDetail["type"] = $type;
		$detail = $DetailModel->where($conditionDetail)->select();
		$dcModule = m('module_product_order_detail_specification');
		$pro=$ProductModel->where('id=' . $pid)->find();
		if($size){
			$specWhere['pid']=array('eq',$pid);
			$specWhere['firstSpecificName']=array('eq',$size);
			$color?$specWhere['secSpecificName']=array('eq',$color):"";
			$priceInfo=$productSpc->where($specWhere)->find();
			$pro['fixedPrice']=$priceInfo['fixedPrice'];
			$pro['discountedPrice']=$priceInfo['discountedPrice'];
			$pro['supplyPrice']=$priceInfo['supplyPrice'];
			$pro['platCut']=$priceInfo['platCut'];
			$pro['saleCut']=$priceInfo['saleCut'];
			$pro['miPrice']=$priceInfo['miPrice'];
			$pro['seckillPrice']=$priceInfo['seckillPrice'];
			$pro['seckillSalce']=$priceInfo['seckillSalce'];
		}
		$countExp="+";
		if($count<0){
			$countExp="";
		}
		Session::switchCustomer($customerId);
		if(self::isEnjoyMiPrice($param)){
			$isEnjoyMiPrice = 1;
		}else{
			$isEnjoyMiPrice = 0;
		}
		Session::switchCustomer(0);
		if($did){
			$result = $DetailModel->query("update wx_module_product_order_detail set `count`=`count`".$countExp.$count." where id=$did");
		} else if ($detail && !$size && !$color) {
			$result = $DetailModel->query("update wx_module_product_order_detail set `count`=`count`".$countExp.$count." where oid=$oid and pid=$pid and userId='".$userId."' and type='$type'");
		} else {
			/*
			$product = $ProductModel->field('price,points')->where("id=$pid")->find();
			if ($product !== false) {
				$data["price"] = $product["price"];
				$data["points"] = $product["points"];
			} */
			if ($detail) {

				foreach ($detail as $k => $v) {
					$where['did']=$v['id'];
					$dspec=$dcModule->where($where)->select();
					if ($color !=null || $size != null) {
						foreach ($dspec as $k1 => $v1) {
							if ($color ==$v1['secSpecificName'] && $size ==$v1['firstSpecificName']) {
								$wheredid['id']=$v['id'];
								$count1=$v['count']+$count;
								$result = $DetailModel->where($wheredid)->setField('count', $count1);
								$num=1;
							}
						}
					}
				}
			}
			$quan=self::getQuanDetail($param->qId);
			if(!$quan){
				reutrn;
			}
			$json = json_decode($pro['json'],true);
			$time = time();
			if (!$num) {
				$platCut=$pro["platCut"];
				$saleCut=$pro["saleCut"];
				if($pro['playType']==5&&$isEnjoyMiPrice){
					$price = $pro["miPrice"];
					$playType = 'miPrice';
				}else if($pro['playType']==4&&$time>strtotime($json['seckillStartTime'])&&$time<strtotime($json['seckillEndTime'])){
					$price = $pro["seckillPrice"];
					$playType = 'seckillPrice';
					$saleCut = $pro['seckillSalce'];
				}else if($pro["discountedPrice"] !== NULL&&$pro["discountedPrice"]>0) {
					$price = $pro["discountedPrice"];
					$playType = 'discounted';
				} else if($pro["fixedPrice"] !== NULL){
					$price = $pro["fixedPrice"];
					$playType = 'fixed';
				}
				$data=array(
					'fromUserName'=>$userName,
					'sId'=>$param->shareId,
					'oid'=>$param->oid,
					'qId'=>$param->qId,
					'miUid'=>$param->miUId,
					'pid'=>$param->pid,
					'squarePicUrl'=>$pro['squarePicUrl'],
					'type'=>$param->type,
					'count'=>$param->count,
					'freePrice'=>$param->deposit,
					'shareFormGuid'=>$param->shareFormGuid,
					'visitId'=>$param->visitId,
					'saleCut'=>$saleCut,
					'platCut'=>$platCut,
					'price'=>$price,
					'playType'=>$playType,
					'customizedInfo'=>$param->customizedInfo,
					'userId'=>$userId
				);
				$result = $DetailModel->add($data);
				if($color !=null){
					$dcData['secSpecificName'] = $color;
				}
				if($size != null){
					$dcData['firstSpecificName'] = $size;
					$dcData['did'] = $result;
					$dcResult = $dcModule->add($dcData);
					if (!$dcResult) {
						Log::write('[productModule updateOrderDetail add spec error]' .$dcModule->getLastSql());
					}
				}
			}
		}
		Session::switchCustomer($customerId);
		if ($result !== false) {
			if ($oid != 0) {
				$product = $ProductModel->field('id, fixedPrice,discountedPrice,points,playType,json,seckillPrice')->where("id=$pid")->find();
				$json = json_decode($product['json'],true);
				$time = time();
				if ($product !== false) {
					// $discount = self::getDiscountPrice($product['id']);
					// $product["discountedPrice"] = $discount['discPrice'];
					$ProductOrderModel = M('module_product_order');
					if($product['playType']==5&&$isEnjoyMiPrice){
						$price = $product["miPrice"];
						$ProductOrderModel->where("id=$oid")->setField("price", $price);
					}else if($pro['playType']==4&&$time>strtotime($json['seckillStartTime'])&&$time<strtotime($json['seckillEndTime'])){
						$price = $product["seckillPrice"];
						$ProductOrderModel->where("id=$oid")->setField("price", $price);
					}else if($product["discountedPrice"] !== NULL) {
						$price = $product["discountedPrice"];
						$ProductOrderModel->where("id=$oid")->setField("price", $price);
					} else if($product["fixedPrice"] !== NULL){
						$price = $product["fixedPrice"];
						$ProductOrderModel->where("id=$oid")->setField("price", $price);
					} else if($product["points"] !== NULL){
						$points = $product["points"];
						$ProductOrderModel->where("id=$oid")->setField("points", $points);
					}
				}
			}
			Output::instance()->resultCode(code_success);
		} else {
			Log::write('[productModule updateOrderDetail add detail error]' . $DetailModel->getLastSql());
			Output::instance()->resultCode(code_sql_error);
		}
	}

	public static function removeOrderDetail($param) {
		$customerId = Session::$user['customerId'];
		$userName = Session::$user['userName'];
		Session::switchCustomer(0);
		$DetailModel = M("module_product_order_detail");
		$pids=$param->pids;
		$DetailModel = M("module_product_order_detail");
		$dids=$param->dids;
		$condition["id"] = array('eq', $dids);
		$detail = $DetailModel->where($condition)->delete();
		Session::switchCustomer($customerId);
		if ($detail) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	public function getQuanDetail($qId){
		$quanModel = M("miyouquan");
		$result=$quanModel->where('id=' . $qId)->find();
		return $result;
	}
	/**
	 * [orderPayCallback 统一的支付回调]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public function orderPayCallback($param) {
		self::rechargeMoney($param); //充值卡商品充值
		self::SendorderNotice($param);	//订单状态改变推送模板消息
		self::deductionPurse($param);
		self::createVirtualCode($param);	//创建虚拟商品验证码
		self::crowdFundingCallback($param);//众筹
		self::tuanOrderPayCallback($param);
		self::SendIndianaCode($param);		//夺宝分配号码
		self::addMiBuyRecord($param);
		self::updateCouponStatus($param);//优惠券变为已使用
		self::sendNoticeToStore($param);
		self::SendQuanOrderNotice($param);	//给合伙人发送模板消息
		self::joinQuanByOrder($param);
		self::isDeliver($param);
	}
	public function isDeliver($param){
        $ids=explode(",",$param->id);
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $OrderModel = M("module_product_order");
        Session::switchCustomer($cid);
        foreach ($ids as $id){
            $whereOrder["id"] = $id;
            $order = $OrderModel->where($whereOrder)->find();
            if(!empty($order["deliverMiUId"]) && $order["deliverMiUId"] != 0 && $order["deliverMiUId"] == $order["uId"]){
                R("Product/updateOrderTipByOrderId",array($id,NULL,NULL,$status='ok',NULL,NULL,1));
            }
        }
    }

	private static function deductionPoint($param, $cid)
	{

		Session::switchCustomer(0);
		$pointModel = D('Point', 'Logic');
		$orderModel = M("module_product_order");
		$orderDetailModel = M('module_product_order_detail');
		Session::switchCustomer($cid);
		$ids=explode(",",$param);

		foreach ($ids as $value) {
			$userId = $orderModel->where("id = $value")->getField('uId');
			$serialNumber = $orderModel->where("id = $value")->getField('serialNumber');
			$proName = $orderDetailModel->where(['oid' => $value])->getField('name');
			$points = $orderModel->where("id = $value")->getField('points');
            $pointModel->deductPoint(
                $userId,
                $points,
                'order',
                $serialNumber,
                '积分兑换',
                '商品名称：' . $proName,
                '',
                '',
                1
            );
		}
        return true;
	}

	/**充值卡商品充值
	 * @param $param
	 */
	private static function rechargeMoney($param)
	{
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$purseBillModel = M('module_user_purse_bill');
		$purseModel = M('module_user_purse');
		$OrderModel = M("module_product_order");
		$orderDetail = M("module_product_order_detail");
		Session::switchCustomer($cid);
		$ids=explode(",",$param->id);
		$userName=$param->userName;
		foreach ($ids as $value) {
			//判断充值卡商品
			$detailWhere['oid'] = $value;
			$orderDetail1 = $orderDetail->where($detailWhere)->select();  //获取订单的商品信息
			Log::write('orderDetail:' . json_encode($orderDetail1));
			//$serialNumber = $OrderModel->where("id = $value")->getField('serialNumber');//获取订单号
			$userId = $OrderModel->where("id = $value")->getField('uId');//获取userId，为确保万无一失从订单里获取
			$cardNum = 0;
			foreach ($orderDetail1 as $item) {
				$purseModel->startTrans();
				$rechargeableCard = $item['rechargeableCard'];//是否为充值卡
				if ($rechargeableCard == 1) { //商品是充值卡类型
					$cardNum++;
					$rechargeAmount = $item['rechargeAmount']; //获取充值卡金额
					$cardCount = $item['count']; //获取购买数量
					$sumMoney = $rechargeAmount * $cardCount; //充值金额为两数相乘

					/*给用户充值*/
					$oldBalance =$purseModel->where("userId = $userId and cid = $cid")->getField('balance');
					(empty($oldBalance)) ? $oldBalance = 0:'';
					$oldTotalRecharge = $purseModel->where("userId = $userId and cid = $cid")->getField('totalRecharge');
					(empty($oldTotalRecharge)) ? $oldTotalRecharge = 0:'';
					$data['balance'] = $oldBalance + $sumMoney;//新余额
					$data['totalRecharge'] = $oldTotalRecharge + $sumMoney;//新累计充值
					$data['updateTime'] = date('Y-m-d H:i:s', time());
					$isHave = $purseModel->where("userId = $userId and cid = $cid")->find();
					if ($isHave) {
						$rechargeRes = $purseModel->where("userId = $userId and cid = $cid")->save($data);
					} else {
						$data['cid'] = $cid;
						$data['userId'] = $userId;
						$rechargeRes = $purseModel->add($data);
					}
					unset($data);

					/*添加充值记录*/
					$data['cid'] = $cid;
					$data['userId'] = $userId;
					$data['module'] = 'order';
					$data['moduleId'] = $value;
					$data['description'] = '在线支付充值';
					$data['money'] = $sumMoney;
					$data['type'] = 0;
					$data['createTime'] = date('Y-m-d H:i:s', time());
					$recordRes = $purseBillModel->add($data);
					unset($data);
				}
			}
			if ($cardNum > 0) {//改变订单状态
				$data['status'] = 'ok';
				$orderRes = $OrderModel->where("id = $value")->save($data);
				$sql3 = $OrderModel->getLastSql();
				Log::write('statusSql:' . $sql3);
				unset($data);
			}
			if ($recordRes && $rechargeRes && $orderRes) {
				$purseModel->commit();

//				$name = $orderDetail->where("oid=$value")->getField("name");
//				$data['first'] = array('value'=> '亲，您已经成功支付！','color'=>"#743A3A");
//				$data['keyword1'] = array('value'=> $descSn,'color'=>'#173177');
//				$data['keyword2'] = array('value'=> $name,'color'=>'#173177');
//				$data['keyword3'] = array('value'=> $descPrice,'color'=>'#173177');
//				$data['keyword4'] = array('value'=> $descTime,'color'=>'#173177');
//				$data['remark'] = array('value'=> '感谢您对本项目的支持！',"color"=>'#008000');
//				WeixinApi::sendTpl($userName, $template_id, $url,$topcolor,$data);
			} else {
				$purseModel->rollback();
			}
		}
	}


	//自提订单通知店员的模板消息
    public function sendNoticeToStore($param){
        $ids=explode(",",$param->id);
        $userName = $param->userName;
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        Session::switchCustomer($cid);
        $TemplateModel = M("template_messages");
        $twhere['status']=array('eq',"vendorDelivering");
        $templatemsg = $TemplateModel->where($twhere)->find();
        $templateId = $templatemsg['templateId'];
        foreach($ids as $key=>$oid){
            $orderInfo = $orderModel->alias("a")
                ->join("inner join wx_customer_user b on a.storeResourceId = b.storeId and b.customerId=a.fromCustomerId")
                ->where("a.id=$oid and b.agent='service' and b.openid <> ''")
                ->field("a.serialNumber,a.price,a.payTime,b.openid")
                ->select();
            foreach($orderInfo as $i=>$order){
                $data['first'] = array('value'=> '亲，财源滚滚，您有新的订单需要处理！','color'=>'#743A3A');
                $data['keyword1'] = array('value'=> $order['serialNumber'],'color'=>'#173177');
                $data['keyword2'] = array('value'=> $order['payTime'],'color'=>'#173177');
                $data['keyword3'] = array('value'=> $order['price'],'color'=>'#173177');
                $data['remark'] = array('value'=> '点击查看详情。','color'=>'#008000');
                $toUser = $order['openid'];
                $template_id = $templateId;
                $url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
                    "&module=employeeManage&method=orderDetail&params=%7B%22id%22%3A$oid%7D";
                $url = urlencode($url);
                $topcolor = "#FF0000";
                WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
            }
        }

    }
	//余额支付订单扣除余额
    public function deductionPurse($param){
        $ids=explode(",",$param->id);
        $userName = $param->userName;
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        $purseModel = M("module_user_purse");
        $purseBillModel = M("module_user_purse_bill");
        Session::switchCustomer($cid);
        $userModel = M("user");
        $userId = $userModel->where("openid='$userName'")->getField("id");
        foreach($ids as $key=>$value){
            $orderInfo = $orderModel->alias("a")
                ->join("inner join wx_module_product_order_detail b on a.id=b.oid")
                ->field("a.purseMoney,a.fromCustomerId,group_concat(b.name) as des")
                ->where("a.id=$value")->group("a.id")->find();
            if($orderInfo['purseMoney']>0){
                $data['cid']=$cid;
                $data['userId']=$userId;
                $data['module']="order";
                $data['moduleId']=$value;
                $data['description']=$orderInfo['des'];
                $data['money']=$orderInfo['purseMoney'];
                $data['type']='1';
                $data['createTime']=date("Y-m-d H:i:s");
                $purseBillModel->add($data);
                $purseWhere = [
                    'userId'    => $userId,
                    'cid'       => $orderInfo['fromCustomerId']
                ];
                $purseInfo = $purseModel->where($purseWhere)->find();
                $data = null;
                $data['balance'] = $purseInfo['balance']-$orderInfo['purseMoney'];
                $data['totalConsume'] = $purseInfo['totalConsume']+$orderInfo['purseMoney'];
                $purseModel->where($purseWhere)->save($data);
            }
        }



    }

	public function crowdFundingCallback($param){//众筹回调
		$id = $param->id;
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$productModel = M("module_product");
		$orderModel = M("module_product_order");
		$specModel = M("module_product_specification");
		$crowdfundingModel = M("module_product_crowdfunding");
		$crowdNumber = M("module_crowdfunding_number");
		Session::switchCustomer($cid);
		$orderInfo = $orderModel->alias("a")
			->join("inner join wx_module_product_order_detail b on a.id = b.oid ")
			->join("inner join wx_module_product_order_detail_specification c on b.id=c.did")
			->join("inner join wx_module_product d on b.pid = d.id")
			->field("a.fromUserName,a.price,a.orderType,d.id,d.json,c.firstSpecificName,c.secSpecificName,b.count")
			->where("a.id = $id")
			->find();
		if($orderInfo['orderType']!=6){
			return;
		}
		$productModel->startTrans();
		$json = json_decode($orderInfo['json'],true);
		if($json['supportSum']){
			$json['supportSum']+=$orderInfo['price'];
		}else{
			$json['supportSum']=$orderInfo['price'];
		}
		if($json['supportPerson']){
			$json['supportPerson']++;
		}else{
			$json['supportPerson']=1;
		}
		if($json['supportSum']>=$json['crowTarget']){
//			$result = $orderModel->alias("a")
//				->join("inner join wx_module_product_order_detail b on a.id=b.oid")
//				->where("b.pid=".$orderInfo['id']." and a.status='supported'")
//				->setField("status",order_status_delivering);
//			if($result===false){
//				$productModel->rollback();
//				return;
//			}
			$data['crowdStatus']=1;//众筹状态0众筹中 1成功 2 结束
		}
		$data['json']=json_encode($json);
		$productResult = $productModel->where("id=".$orderInfo['id'])->save($data);
		if($productResult===false){
			$productModel->rollback();
			return;
		}
		$crowdInfo = $specModel->alias("a")
			->join("inner join wx_module_product_crowdfunding b on a.firstSpecificId = b.specId and a.pid=b.pid")
			->field("b.*")
			->where("a.pid = ".$orderInfo['id']." and a.firstSpecificName = '".$orderInfo['firstSpecificName']."' and a.secSpecificName = '".$orderInfo['secSpecificName']."'")
			->find();
		$data['supportPerson']=$crowdInfo['supportPerson']+1;
		if($crowdInfo['restrictPerson']){
			$data['surplusPerson']=$crowdInfo['surplusPerson']-1;
		}
		$data['supportAmount']=$crowdInfo['supportAmount']+$orderInfo['count'];
		if($crowdInfo['restrictAmount']){
			$data['surplusAmount']=$crowdInfo['surplusAmount']-$orderInfo['count'];
		}
		$crowdResult = $crowdfundingModel->where("id=".$crowdInfo['id'])->save($data);
		if($crowdResult===false){
			$productModel->rollback();
			return;
		}
		//抽奖当分配号码
		if($crowdInfo['drawStall']){
			$number = $crowdNumber->where("cid=$cid and pid = ".$orderInfo['id']." and stallId=".$crowdInfo['id'])->field("max(number) as number")->find();
			if($number['number']){
				$number = $number['number']+1;
			}else{
				$number = 100001;
			}
			$data['cid']=$cid;
			$data['stallId']=$crowdInfo['id'];
			$data['oid']=$id;
			$data['userName']=$orderInfo['fromUserName'];
			$data['pid']=$orderInfo['id'];
			$data['createTime']=date("Y-m-d H:i:s");
			$data['number']=$number;
			$crowdResult = $crowdNumber->add($data);
			if($crowdResult===false){
				$productModel->rollback();
				return;
			}
		}
		$productModel->commit();
	}
	public function joinQuanByOrder($param){
		$id = $param->id;
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$orderModel = M("module_product_order");
		$myqModel = M("miyouquan");
		Session::switchCustomer($cid);
		$orderInfo = $orderModel->alias("a")
			->join("inner join wx_".$cid."_user b on a.uId=b.id")
			->join("inner join wx_".$cid."_user_weixin_info c on b.id=c.userId")
            ->join("wx_module_product_order_detail as d on a.id=d.oid")
			->field("a.qId,a.miUid,b.wxNumber,a.orderType,c.openid,d.pid")
			->where("a.id=$id")->find();
		if($orderInfo['orderType']!=4){
			return;
		}
        $joinPid = $myqModel->where(['id' => $orderInfo['qId']])->getField('joinPid');
		$joinPid = json_decode($joinPid, true);
		foreach ($joinPid as $key => $value){
		    if($value['pid'] == $orderInfo['pid']){
                $rankId = $value['rankId'];
            }
        }
		$quaParams = new stdClass();
		$quaParams->userName = $orderInfo['openid'];
		$quaParams->id = $orderInfo['qId'];
		$quaParams->miUId=$orderInfo['miUid'];
		$quaParams->wxId =$orderInfo['wxNumber'];
		$quaParams->rankId =$rankId;
		$quaParams->oid =$id;
		Module::callModule("quan",null,"subscribeRegQuanUser",$quaParams);
	}
	public function updateCouponStatus($param){
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$OrderModel =M("module_product_order");
		$userCoupon = M("module_user_coupon");
		Session::switchCustomer($customerId);
		$oid=explode(",",$param->id);
		$where['id']=array("in",$oid);
		$orderInfo = $OrderModel->where($where)->field('group_concat(userCouponId) as userCouponId')->find();
		if($orderInfo['userCouponId']){
			$userCouponId = explode(",",$orderInfo['userCouponId']);
			$couponWhere['id']=array("in",$userCouponId);
			$userCoupon->where($couponWhere)->setField("status",1);
		}

	}
	/**
	 * [addMiBuyRecord 针对个人限购添加记录]
	 * @param [type] $oid [description]
	 */
	public function addMiBuyRecord($params){
		//针对个人限购，新增购买记录
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MiBuyModel=M("mibuy_limit");
		$OrderModel =M("module_product_order");
		Session::switchCustomer($customerId);
		$oid=$params->id;

		$productList=$OrderModel->alias("a")
		->join("inner join wx_module_product_order_detail b on b.oid=a.id")
		->join("inner join wx_module_product c ON b.pid=c.id")
		->field("c.id,a.uId,b.count,c.limitbuy,a.fromUserName")
		->where("a.id=$oid")->select();
		foreach ($productList as $key => $pro) {
			$pid=$pro["id"];
			$reserveCount=$pro["count"];
			if($pro["limitbuy"]=="1") { //如果是各人限购
				//判断是否是密友
				$data=array(
					"uId"=>$pro["uId"],
					"openid"=>$pro["fromUserName"],
					"pid"=>$pid,
					"count"=>$reserveCount,
					"createTime"=>date("Y-m-d H:i:s")
				);
				$MiBuyModel->add($data);
			}
		}
	}
	public function getTeamCount($teamId) {
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
	    $OrderModel = M("module_team_order");
		$DetailModel = M("module_team_order_detail");
		Session::switchCustomer($customerId);
		$count=$DetailModel->alias("a")
		->join("inner join wx_module_product_order b on a.oid=b.id")
		->where("a.teamId=$teamId and b.wxTransactionId <> ''")->count();
		return $count;
	}
	public function tuanOrderPayCallback($params) {
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $oid=$params->id;
	    $VerifyCode = M("module_verify_code");
	    Session::switchCustomer(0);
	    $OrderTeamModel = M("module_team_order");
	    $OrderModel = M("module_product_order");
		Session::switchCustomer($customerId);

	    $orderInfo=$OrderModel->where("id=$oid")->find();
	    Log::write($OrderModel->getlastsql());

	    if(!$orderInfo || $orderInfo["isTeam"]!="1") {
	    	return;
	    }
	    $teamId=$orderInfo["teamId"];
	    if(!$teamId) {
	    	return;
	    }
	    $teamInfo=$OrderTeamModel->where("id=$teamId")->find();
		$proInfo=$OrderTeamModel->alias("a")
	    ->join("inner join wx_module_product b on a.pid=b.id")
	    ->field("a.status,b.teamCount")->where("a.id=$teamId")
	    ->find();

	    if($orderInfo["isVirtual"]==1) {
			$status="delivered";
		} else {
			$status="delivering";
		}
	    if($proInfo["status"] > 0) { //如果组团成功了,直接更新订单状态为等待发货
	    	$OrderModel->where("id=$oid")->setField("status",$status);
	    }
	    if(!$teamInfo || $teamInfo["status"] > 0) {
	    	return;
	    }
	    $teamCount=self::getTeamCount($teamId);
	    if($teamCount>=$proInfo["teamCount"]) {
			$OrderTeamModel->startTrans();
			$upTeamOrderData["status"]="1";
			$updateTemp=$OrderTeamModel->where("id=$teamId")->save($upTeamOrderData);
			$updateOrder=$OrderModel->where("teamId=$teamId and status='teaming'")->setField("status",$status);
			if($orderInfo["isVirtual"]=="1") { //虚拟商品订单，更新验证码为可用
				$coders=$OrderTeamModel->alias("a")
				->join("inner join wx_module_team_order_detail d on d.teamId=a.id")
				->join("inner join wx_".$customerId."_module_verify_code c on c.oid=d.oid")
				->field("c.id")
				->where("a.id=$teamId")->select();
				foreach ($coders as $key => $code) {
					$updateCode=$VerifyCode->where("id=".$code["id"])->setField("disabled",1);
					if($updateCode===false) {
						$OrderTeamModel->rollback();
					}
				}
			}
			if($updateOrder!==false && $updateTemp!==false) {
				$OrderTeamModel->commit();
			} else {
				$OrderTeamModel->rollback();
			}
		}
	}
	/**
	 * [checkMiUserAndLimit 密友限购检查]
	 * @return [type] [description]
	 */
	public function checkMiUserAndLimit($productList,$uId){
		$customerId = Session::$user['customerId'];
		$userName = Session::$user["userName"];
		Session::switchCustomer(0);
		$quanModel=M("quan_user");
		$miBuyModel=M("mibuy_limit");
		Session::switchCustomer($customerId);
		$result=self::isPartner();
		$out["code"]=0;
		foreach ($productList as $key => $pro) {
			$pid=$pro["id"];
			$reserveCount=$pro["reserveCount"];
			if($pro["specialpro"]=="1") { //如果是密友特供商品
				//判断是否是密友
				if (!$result || count($result) < 1) {
					$out["code"] = 1;
					if (count($productList) > 1) {
						$out["msg"] = "商品【" . $pro["name"] . "】为密友特供商品，非密友不能购买";
					} else {
						$out["msg"] = "本商品为密友特供商品，非密友不能购买";
					}
					break;
				}
			}
			if($pro["limitbuy"]==1){ //判断是否限购
				if($pro["limitbuy"]==1) {
					$count=$miBuyModel->alias("a")->where("a.openid='$userName' and a.pid=$pid")->sum("a.count");
					if(!$count){
						$count=0;
					}
					$reserveCount=$reserveCount+$count;
					if($reserveCount > $pro["limitnum"]) {
						if(count($productList) > 1) {
							$out["msg"]="商品【".$pro["name"]."】超过个人限购数量";
						} else {
							$out["msg"]="本商品超过个人限购数量";
						}
						$out["code"]=1;
						break;
					}
				}
			}
		}
		return $out;
	}

	public static function preSubmitOrder($param,$noNeedJsonResult=true) {
		$token=$param->token;
		$token = Module::callModule("personCenter",null,"verifyToken",$token);
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$userName = Session::$user['userName'];
		$uId=Session::$user['userId'];
//		$UserInfo = get_UserInfo_by_fromUserName($uId);		//LP修改
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);

		$userPointModel = M('module_user_point');
		$miMallUserModel=M("mimall_user");
		$miyouquan=M("miyouquan");
		$quanuser = M("quan_user");
		$agentModel = M("vendor_agent");
		$OrderModel = M("module_product_order");
		$DetailModel = M("module_product_order_detail");
		$specModel = M("module_product_order_detail_specification");
		$MiQuanRankModel = M('miyouquan_setting_rank');
		Session::switchCustomer($customerId);
		$user_tab = M('user');
		$pids=$param->pids;
		$counts=$param->counts;
		$type=$param->type;
		$sid=$param->sid;
		$sizes=$param->sizes;
		$dids=$param->dids;
		$colors=$param->colors;
		$module=$param->module;
		$method=$param->method;
		$moduleId=$param->moduleId;
		$deposits=$param->deposits; //自由购商品订金
		$teamBuyType=$param->teamBuyType; //团购
		$distributionId = $param->distributionId;
		$IDName = $param->IDName;
		$IDNumber = $param->IDName;
		$proSource = $param->proSource;
		$miUId=$param->miUId;
		$qId=$param->qId;
		$customizedInfo = $param->customizedInfo;
		$regInfo = $param->regInfo;
		$isJoinQuan = $param->isJoinQuan;			//是否为注册订单
		if($dids){
			$productList = self::getCartProduct($type,$userName,$dids);
			foreach($productList as $key=>$value){
				if($value['qId']&&$value['miUid']){
					$qId = $value['qId'];
					$miUId = $value['miUid'];
					break;
				}
			}
		} else if (strstr($pids, ',') || (!strstr($pids, ',') && $pids != -1)) {
			$isCommonPro = 1;//侯佳2018-02-12添加

			$productList = self::getPreSubmitOrderProduct($pids, $counts,$deposits,$teamBuyType,$sizes,$colors,$type);
			if ($productList == false) {
				Output::instance()->object([
					'code' => 3,
					'msg' => '充值卡商品不可与其他商品同时购买'
				]);
				return;
			}
		} else {
			$productList = self::getCartProduct($type,$userName,'');
		}

		$isMiUserPro=self::checkMiUserAndLimit($productList,$uId);
		if($isMiUserPro["code"]==1) {
			if($noNeedJsonResult){
				Output::instance()->resultCode($isMiUserPro["code"],$isMiUserPro["msg"]);
				return;
			}else{
				return null;
			}
		}

		$tempParam = new stdClass();
		$tempParam->qId = $qId;
		$tempParam->miUId =$miUId;
		if(self::isEnjoyMiPrice($tempParam)){
			$isEnjoyMiPrice = 1;
		}else{
			$isEnjoyMiPrice = 0;
		}
		$miUser=$miMallUserModel->where("uId='".$uId."' and cId=".$customerId)->find();
		if(!$miUId || !$qId){ //如果购买参数不带密友相关信息，从之前的购买关系表中查找
			$miUserInfo = $quanuser->where(['uid'=>$miUser['miUid'], 'qid'=>$miUser['qId'], 'deleted'=>0,'status'=>1])->find();
			Log::write("取锁定用户表信息   ".$miMallUserModel->getLastSql()."--".$miUser["miUid"]);
			if($miUserInfo){
				if($miUser && count($miUser) > 0){
					$uId=$miUser["uId"];
					$miUId=$miUser["miUid"];
					$qId=$miUser["qId"];
					$saleSource = $miUser['saleSource'];
				}
			}
		}
		$refereeInfo = null;
		if($miUId&&$qId){
			$refereeInfo = $quanuser->alias("a")
				->join("wx_quan_user b on a.refereeUid = b.uid and a.qid = b.qid and b.status=1 and b.deleted=0")
				->where("a.qid = $qId and a.uid=$miUId and a.status=1 and a.deleted=0")
				->field("a.isMiUDeliver,a.refereeUid,b.refereeUid as parentRefereeUid,a.saleSource")
				->find();
		}
		$saleSource = $refereeInfo['saleSource']?$refereeInfo['saleSource']:$saleSource;
		$pay = self::getProductPay($productList, $counts,null,$isEnjoyMiPrice);
		if (!isset($pay)) {
			return;
		}

		if($type == 'form' && !empty($customizedInfo)){
			$formValArr = json_decode(json_encode($customizedInfo),true);
			foreach($formValArr as $k=>$v){
				switch($v['type']){
					case'name':
						$fullName = $v['value'];
						break;
					case 'phone':
						$phone = $v['value'];
						break;

					case 'email':
						$email = $v['email'];
						break;
					//mh添加需验证的手机号类型20180127
					case 'verifyPhone':
						$phone = $v['value'];
						$verifyPhone = 1;
						break;
					case 'city':
						$province = $v['value']['provice'];
						$city = $v['value']['city'];
						$county= $v['value']['county'];
						break;
					case 'address':
						if(!empty($v['city']['provice'])){
							$province = $v['city']['provice'];
							$city = $v['value']['city'];
							$county= $v['value']['county'];
						}
						$address = $v['value'];
						break;
					default:
						break;
				}
			}
		}else if($customizedInfo){
			$customized = json_decode($customizedInfo,true);
			foreach($customized as $key=>$value){
				if($value['type']==3){
					$fullName = $value['description'];
				}else if($value['type']==4){//mh20180127注释：这是需要验证的手机号，之后和下面的类型一起添加
					$phone = $value['description'];
				}else if($value['type']==6){
					$other = $value['other'];
					$province = $other['province'];
					$city = $other['city'];
					$country = $other['country'];
				}//mh20180127这里之后要增加一种类型，不需要验证的手机号类型
			}
		}
		//mh添加手机号验证代码，加在这里是因为下面就要更新user表中的信息了。20180127
		if ($verifyPhone == 1){
			$phone_params = new StdClass();
            $phone_params->phone = $phone;
            Module::callModule('phone', NULL, 'verifyPhone', $phone_params);
		}
		//--------
		$quan=self::getQuanDetail($qId);
		$vendorPrice = $pay["vendorPrice"];
		$resultOid = array();
		/*更新user表中的信息jie*/
		$userInfo = $user_tab->where(['id' => $uId])->find();
		$userData = [];
		if($fullName){
			!empty($userInfo['fullName'])? '' : $userData['fullName'] = $fullName;
		}
		if($verifyPhone){
			//LP 修改 判断是否更新手机号
			$UserCount = $user_tab->where(['phone' => $userInfo['phone']])->count();
			if($UserCount == 0){
				!empty($userInfo['phone'])? '' : $userData['phone'] = $verifyPhone;
				!empty($userInfo['phone'])? '' : $userData['isVerifyPhone'] = 1;
			}
		}
		if($phone){
			//LP 修改 判断是否更新手机号
			$UserCount = $user_tab->where(['phone' => $userInfo['phone']])->count();
			if($UserCount == 0){
				!empty($userInfo['phone'])? '' : $userData['phone'] = $phone;
			}
		}
		if($email){
			!empty($userInfo['email'])? '' : $userData['email'] = $email;
		}
		if(!$userInfo['province']){
			if($province){
				$userData['province'] = $province;
			}
			if($city){
				$userData['city'] = $city;
			}
			if($county){
				$userData['county'] = $county;
				$userData['town'] = '';
				$userData['rural'] = '';
			}
		}

		if($address){
			$userData['address'] = $address;
		}
		$user_tab->where(['userName'=>$userName])->save($userData);
		foreach($vendorPrice as $key=>$value) {
			$data = array(
				'fullName' => $fullName,
				'phone' => $phone,
				'province' => $province,
				'city' => $city,
				'country' => $country,
				'address' => $address,
				'fromUserName' => $userName,
				'fromCustomerId' => $customerId,
				'type' => $type,
				'points' => $pay["points"],
				'status' => order_status_notsubmit,
				'createTime' => date("Y-m-d H:i:s"),
				'qId' => $qId,
				'uId' => $uId,
				'distributionId'=>$distributionId,
				'proSource'=>$proSource,
				/*'miUid' => $miUId,
				'refereeUid'=>$refereeInfo['refereeUid'],
				'parentRefereeUid'=>$refereeInfo['parentRefereeUid'],*/
				'saleSource'=>$saleSource,
				'vId' => $value["vId"],
				'module' => $module,
				'method' => $method,
				'moduleId' => $moduleId,
				'IDName'=>$IDName,
				'IDNumber'=>$IDNumber,
				'miAward' => $quan["miAward"],
				'lordAward' => $quan["lordAward"],
				'refueMoney' => 0,
				'updateTime' => date("Y-m-d H:i:s"),
				'recommenderId' => $miUser['recommenderId']
			);
			/*根据圈子分成记录层级*/
            if($quan['cutRank'] == 3){
                $data['miUid'] = $miUId;
                $data['refereeUid'] = $refereeInfo['refereeUid'];
                $data['parentRefereeUid'] = $refereeInfo['parentRefereeUid'];
            }

            if($quan['cutRank'] == 2){
                $data['miUid'] = $miUId;
                $data['refereeUid'] = $refereeInfo['refereeUid'];
            }
            if($quan['cutRank'] == 1){
                $data['miUid'] = $miUId;
            }



			if ($pay["freebuy"] == "1" && $pay["priceFree"] != $pay["price"]) { //自由购
				$data["freebuy"] = 1;
				$data["price"] = $pay["priceFree"];
			} else if ($pay["teambuy"] == "1") {
				$data["price"] = $value["price"];
			} else if ($pay["playType"] == "3") {
				$data["orderType"] = 3;
				$data["price"] = $value["price"];
			} else if($pay["playType"]==5&&$isEnjoyMiPrice){
				$data["price"] = $value["price"];
			}else if($pay["playType"]==6){
				$data["orderType"] = 6;
				$data["price"] = $value["price"];
			}else if($pay["playType"]==7){
				$data["orderType"] = 7;
				$data["price"] = $value["price"];
			} else if($type == ORDER_TYPE_FORM){	//表单订单
				$data["orderType"] = ORDER_ORDERTYPE_NINE;
				if($value['isPay'] == 1){
					$data['status'] = ORDER_STATUS_PAYING;
					$data["price"] = $value["price"];
				}else{
					$data["price"] = 0;
					$data['status'] = order_status_submission;
				}
			}else{
				$data["price"] = $value["price"];
			}
			if ($pay["virtual"] == "1") { //虚拟商品
				$data["isVirtual"] = "1";
			}
			if($pay["isActivity"] == "1"){
				$data["isActivity"] = "1";
			}
			if($value['isChainPro']){
				$data['isChainOrder']=1;
				$data['supplyChainId']=$value['supplyChainId'];
			}
			if($refereeInfo['isMiUDeliver'] == 1){
                $data['deliverMiUId'] = $miUId;
            }

			//<侯佳添加2018-02-13：判断是积分订单，支付金额为0，将支付积分写入订单>

			if ($type == ORDER_TYPE_POINT) {
				$data['price'] = 0.00;
				$pointBalance = $userPointModel->where(['cid' => $customerId, 'userId' => $uId])->getField('pointBalance');
				if (empty($pointBalance)) $pointBalance = 0;
				if ($pay['points'] < 0) {
					Output::instance()->object([
						'code' => 3,
						'msg' => '购买的商品中包含非积分兑换商品'
					]);
					return;
				}
				if ($pointBalance < $pay['points']) {
					Output::instance()->object([
						'code' => 2,
						'msg' => '积分余额不足'
					]);
					return;
				} else {
					$data['points'] = $pay['points'];
				}

			}
			//</侯佳添加2018-02-13>



			$vendorPrice[$key]["oid"] = $OrderModel->add($data);
            if($vendorPrice[$key]["oid"] && $type == ORDER_TYPE_FORM  && $value['isPay'] != 1){
                $idArray[0] = $vendorPrice[$key]["oid"];
                R("StatisTics/statisOrder", array($idArray, $customerId));
            }
			array_push($resultOid,$vendorPrice[$key]["oid"]);
		}
		if ($vendorPrice[0]["oid"]) {
			$resultDetail = true;
            $userAward = null;
			if($isJoinQuan == 1){
                $quanInfo = $miyouquan->where("id=$qId")->find();
                $userAward = $quanInfo['joinQuanUserAward'];
                $miAward = $quanInfo['joinQuanMiAward'];
                $refereeAward = $quanInfo['joinQuanRefereeAward'];
                $parentRefereeAward = $quanInfo['joinQuanParentRefereeAward'];

            }else{
                $miuRankAward = null;
                if($miUId){
                    $rankWhere['quser.qid'] = array('eq', $qId);
                    $rankWhere['quser.uId'] = array('eq', $miUId);
				$rankWhere['rankId'] = array('neq', 0);
				$rankWhere['deleted'] = array('eq', 0);
                    $miuRankAward = $quanuser->alias('quser')->join('wx_miyouquan_setting_rank rank on quser.rankId=rank.id')->where($rankWhere)->find();
                }
                if(!empty($miuRankAward)){
                    $miAward = $miuRankAward['miAward'];
                    $refereeAward = $miuRankAward['refereeAward'];
                    $parentRefereeAward = $miuRankAward['parentRefereeAward'];
                }else{
                    $quanInfo = $miyouquan->where("id=$qId")->find();
                    $miAward = $quanInfo['miAward'];
                    $refereeAward = $quanInfo['refereeAward'];
                    $parentRefereeAward = $quanInfo['parentRefereeAward'];
                }
            }


			$lordAward = 1;
			if($type == ORDER_TYPE_FORM){
				$vid = $vendorPrice[0]['vId'];
			}else{
				$vid = $param->vId;
			}
			$agentInfo = $agentModel->where("find_in_set(".$vid.",vendors)")->find();
			$agentAward = $agentInfo['agentAward'];
			$platAward = 1-$agentAward;
			if ($pids !== -1) {
				$arrPid = explode(",", $pids);
				$arrCount = explode(",", $counts);
				$arrDeposit = explode(",", $deposits);
			}
			$i = 0;

			foreach ($productList as $pro) {
				foreach($vendorPrice as $index=>$vid){
					if($vid['vId']==$pro["vId"]){
						$result=$vid["oid"];
						break;
					}
				}

				$dataDetail["oid"] = $result;
				$dataDetail['rechargeableCard'] = $pro['rechargeableCard'];
				$dataDetail['rechargeAmount'] = $pro['rechargeAmount'];
				$dataDetail["userId"] = $uId;


				$dataDetail["freePrice"]=$pro["freePrice"];
				$platCut=$pro["platCut"];
				$saleCut=$pro["saleCut"];
				if ($type == ORDER_TYPE_POINT) {
					$pro["platCut"] = 0;
					$pro["saleCut"] = 0;
				}
				$dataDetail["fromUserName"] = $userName;
				$dataDetail["storeId"] = $sid;

				$dataDetail["pid"] = $pro["id"];
				$dataDetail["type"] = $type;
				if(!$dids && $arrCount) {
					$dataDetail["count"] = $arrCount[$i];
					$json = json_decode($pro["json"],true);
					if($pro["teambuy"]&&$pro["teamBuyType"]=="team"){
						$dataDetail["price"] = $pro["teamPrice"];
						$dataDetail['playType']='team';
					}else if($pro["playType"]==3){
						$dataDetail["price"] = $pro["perMoney"];
						$dataDetail['playType']='indiana';
					}else if($pro["playType"]==5&&$isEnjoyMiPrice==1){
						$dataDetail["price"] = $pro["miPrice"];
						$dataDetail['playType']='miPrice';
					}else if($pro["playType"]==4&&strtotime($json['seckillStartTime'])<time()&&strtotime($json['seckillEndTime'])>time()){
						$dataDetail["price"] = $pro["seckillPrice"];
						$dataDetail['playType']='seckillPrice';
						$saleCut = $pro['seckillSalce'];
						$pro['saleCut'] = $pro['seckillSalce'];
					}else if($pro["discountedPrice"]&&$pro["discountedPrice"]>0) {
						$dataDetail["price"] = $pro["discountedPrice"];
						$dataDetail['playType']='discounted';
					}else {
						$dataDetail["price"] = $pro["fixedPrice"];
						$dataDetail['playType']='fixed';
					}
					$dataDetail['customizedInfo']=$customizedInfo;
					/*营销订单*/
					if($type == ORDER_TYPE_FORM){
						if($vendorPrice[0]['isPay'] == 1){
							$dataDetail["price"] = $pro["price"];
							$pro['fixedPrice'] = $pro["price"];
						}else{
							$pro['supplyPrice'] = 0;	//营销订单不需要支付
							$dataDetail["price"] = 0;
						}
						$dataDetail['qId']=$qId;
						$dataDetail['miUid']=$miUId;
						$dataDetail['playType']='fixed';
						$dataDetail['contentId']=$moduleId;
						$dataDetail['customizedInfo']=json_encode($customizedInfo,JSON_UNESCAPED_UNICODE);
					}
				} else {
					$dataDetail["count"] =$pro["reserveCount"];
					$dataDetail["price"] =$pro['price'];
					$dataDetail['qId']=$pro['qId'];
					$dataDetail['miUid']=$pro['miUid'];
					$dataDetail['playType']=$pro['detailPlayType'];
					$dataDetail['customizedInfo']=$pro['customizedInfo'];
				}
				if(!empty($userAward)){
                    $dataDetail['userRatio']=$userAward;
                    $dataDetail['isUserCut']=$pro['saleCut']*$userAward*$dataDetail["count"];
                    if ($type == ORDER_TYPE_POINT) $dataDetail['isUserCut'] = 0;
                    $lordAward-=$miAward;
                }
				if($qId&&$miUId){
					$dataDetail['miUserRatio']=$miAward;
					$dataDetail['isMiUserCut']=$pro['saleCut']*$miAward*$dataDetail["count"];
					if ($type == ORDER_TYPE_POINT) $dataDetail['isMiUserCut'] = 0;
					$lordAward-=$miAward;
				}

				if($qId&&$refereeInfo['refereeUid']){
					$dataDetail['refereeRatio']=$refereeAward;
					$dataDetail['isRefereeCut']=$pro['saleCut']*$refereeAward*$dataDetail["count"];
					if ($type == ORDER_TYPE_POINT) $dataDetail['isRefereeCut'] = 0;
					$lordAward-=$refereeAward;
				}
				if($qId&&$refereeInfo['parentRefereeUid']){
					$dataDetail['parentRefereeRatio']=$parentRefereeAward;
					$dataDetail['isParentRefereeCut']=$pro['saleCut']*$parentRefereeAward*$dataDetail["count"];
					if ($type == ORDER_TYPE_POINT) $dataDetail['isParentRefereeCut'] = 0;
					$lordAward-=$parentRefereeAward;
				}
				if($qId&&$miUId){
					$dataDetail['lordRatio']=$lordAward;
					$dataDetail['isLordCut']=$pro['saleCut']*$lordAward*$dataDetail["count"];
					if ($type == ORDER_TYPE_POINT) $dataDetail['isLordCut'] = 0;
				}
				$dataDetail['agentRatio']=$agentAward;
				$dataDetail['platRatio']=$platAward;
				$dataDetail['isVendorCut']=$pro['supplyPrice']*$dataDetail["count"];
				$dataDetail['isChannelCut']=$pro['channelSupplyPrice']*$dataDetail["count"];
				$dataDetail['isAgentCut']=$pro['platCut']*$agentAward*$dataDetail["count"];
				$dataDetail['isPlatCut']=$pro['platCut']*$platAward*$dataDetail["count"];
				$tempAgentInfo = $agentModel->where("find_in_set(".$pro['vId'].",vendors)")->find();
				$tempAgentAward = $tempAgentInfo['agentAward'];
				$tempPlatAward = 1-$tempAgentAward;
				$dataDetail['isAgentCut']=$pro['platCut']*$tempAgentAward*$dataDetail["count"];
				$dataDetail['isPlatCut']=$pro['platCut']*$tempPlatAward*$dataDetail["count"];
				$dataDetail["sId"]=$pro['sid'];
				$dataDetail["shareFromGuid"]=$param->shareFromGuid;
				$dataDetail["visitId"]=$param->visitId;
				$dataDetail["saleCut"]=$saleCut;
				$dataDetail["platCut"]=$platCut;
				$dataDetail["name"]=$pro["name"];
				$dataDetail["foreignName"]=$pro["foreignName"];
				$dataDetail["supplierSkuNo"]=$pro["supplierSkuNo"];
				if($type == ORDER_TYPE_FORM){
					$dataDetail["supplierSkuNo"]=0;
				}
				$dataDetail["country"]=$pro["country"];
				if($pro['supportSpecification']!=1 && $type !== ORDER_TYPE_FORM){
					$dataDetail["specificUnit"]=$pro["specificUnit"];
					$dataDetail["specification"]=$pro["specification"];
					$dataDetail["specificName"]=$pro["specificName"];
				}
				if($type == ORDER_TYPE_FORM){
					//等表单分类完成后再进行扩展
				}else{
					$dataDetail['category'] = self::getProTagName($pro['id']);
				}

				$dataDetail["fixedPrice"]=$pro['fixedPrice'];
				$dataDetail['discountedPrice']=$pro['discountedPrice'];
				$dataDetail['picUrl']=$pro['picUrl'];
				$dataDetail['squarePicUrl']=$pro['squarePicUrl'];
				if(is_array($pro['picUrl1'])){
					$dataDetail['picUrl1']=json_encode($pro['picUrl1']);
				}else{
					$dataDetail['picUrl1']=$pro['picUrl1'];
				}
				$dataDetail['serialNumber']=$pro['serialNumber'];
				$dataDetail['weight']=$pro['weight'];
				$dataDetail['deliveryCode']=$pro['deliveryCode'];
				$dataDetail['customsName']=$pro['customsName'];
				$dataDetail['customsPrice']=$pro['customsPrice'];
				$dataDetail['tariff']=$pro['tariff'];
				$dataDetail['ppat']=$dataDetail["count"]*$dataDetail['tariff']*$dataDetail['customsPrice'];
				$dataDetail['points']=$pro['points'];//侯佳2018-02-13添加
				/*<侯佳2018-02-12添加：将积分获取情况写进订单>*/
				if (isset($isCommonPro) && $isCommonPro == 1 && $type != ORDER_TYPE_POINT) {
					Session::switchCustomer(0);
					$pointSchModel = M('module_point_scheme');
					Session::switchCustomer($customerId);

					/*将线索积分方案写入订单详情表*/
					if($type == ORDER_TYPE_FORM){
						$properties = $pro['property'];
						$pointSchId = $pro['pointSchemeId'];
						$schemeName = $pro['schemeName'];
					}else{
						$defaultId = $pointSchModel->where(['cid' => $customerId, 'default' => 1])->getField('id');//获取默认方案的id
						$pointSchId = $pro['pointsType'];
						(empty($pointSchId)) ? $pointSchId = $defaultId : '';//积分方案id为空，就为默认方案

						$pointSchWhere['id'] = $pointSchId;
						$pointSchWhere['cid'] = $customerId;
						$pointSchWhere['status'] = 1;
						$properties = $pointSchModel->where($pointSchWhere)->getField('property');
						$schemeName = $pointSchModel->where($pointSchWhere)->getField('name');
					}
					if (!empty($properties)) {
						$arrProperty = json_decode($properties, true);
						if($type == ORDER_TYPE_FORM){
							//和线索关联的积分方案
							foreach ($arrProperty as $k=>$v) {
								if ($v['type'] == POINT_TYPE_FORM_ORDER && $v['status'] == 1) {
									$keyProperty = $v;
									break;
								}
							}
						}else{
							foreach ($arrProperty as $property) {
								if ($property['type'] == property_type_buy_pro && $property['status'] == 1) {//积分属性是购买商品获得积分方式
									$keyProperty = $property;
								}
							}
						}

						if (isset($keyProperty)) {
							if($type == ORDER_TYPE_FORM){
								$buyerPoint = $keyProperty['buyerPoint'];
								$miPoint = $keyProperty['miPoint'];
								$preMiPoint = $keyProperty['preMiPoint'];
								$prePreMiPoint = $keyProperty['prePreMiPoint'];
								$recommenderPoint = $keyProperty['recommenderPoint'];
							}else {
								$buyerPoint = round($dataDetail["price"] * $keyProperty['buyerPercentage'] / 100) * $dataDetail["count"];
								$miPoint = round($dataDetail["price"] * $keyProperty['miPercentage'] / 100) * $dataDetail["count"];
								$preMiPoint = round($dataDetail["price"] * $keyProperty['preMiPercentage'] / 100) * $dataDetail["count"];
								$prePreMiPoint = round($dataDetail["price"] * $keyProperty['prePreMiPercentage'] / 100) * $dataDetail["count"];
								$recommenderPoint = round($dataDetail["price"] * $keyProperty['recommenderPercentage'] / 100) * $dataDetail["count"];
								if ($keyProperty['noMiPoint'] && $uId == $miUId) $buyerPoint = 0;//如果下单人是注册好友，只获得推荐积分
								if ($keyProperty['registerNoPoint'] && $isJoinQuan == 1) $miPoint = $preMiPoint = $prePreMiPoint = $recommenderPoint = 0;//如果是注册订单，只有注册人有积分
							}
							$pointConfig = [
							'pointSchId' => $pointSchId,
							'schemeName' => $schemeName,
							'buyerPoint' => $buyerPoint,
							'miPoint' => $miPoint,
							'preMiPoint' => $preMiPoint,
							'prePreMiPoint' => $prePreMiPoint,
							'recommenderPoint' => $recommenderPoint
							];

							$dataDetail['pointConfig'] = json_encode($pointConfig);
						}
					}

				}
				/*</侯佳2018-02-12添加>*/
				/*孟慧2018-04-09添加，用于在订单详情中添加任务信息，修改任务消息存取方式【开始】*/

                if ($pro['taskModel']) {
                    $configJson = json_decode($pro['json'],true);
                    $dataDetail['taskInfo'] = $configJson['taskInfo'];
                    $dataDetail['taskModel'] = 1;
                }
                /*孟慧2018-04-09添加，用于在订单详情中添加任务信息，修改任务消息存取方式【结束】*/
				//<侯佳添加于2018-04-11，积分订单将订单详情表价格置为0>
				if ($type == ORDER_TYPE_POINT) {
					$dataDetail['price'] = 0;
				}
				//</侯佳添加于2018-04-11，积分订单将订单详情表价格置为0>

				$resultTemp = $DetailModel->add($dataDetail);
				if ($resultTemp === false) {
					$resultDetail = false;
				} else {
					if (($productList[$i]["supportSpecification"] == 1) && ($sizes != null || $colors != null)) {
						if ($sizes != null) {
							$arrFirstSpecs = explode(",", $sizes);
							$firstSpecName = $arrFirstSpecs[$i];
						} else {
							$firstSpecName = '';
						}
						if ($colors != null) {
							$arrSecSpecs = explode(",", $colors);
							$secSpecName =  $arrSecSpecs[$i];
						} else {
							$secSpecName = '';
						}

						$dataClothes["did"] = $resultTemp;
						$dataClothes["firstSpecificName"] = $firstSpecName;
						$dataClothes["secSpecificName"] = $secSpecName;
						$dataClothes["firstSpecificUnit"] = $pro["firstSpecificUnit"];
						$dataClothes["secSpecificUnit"] = $pro["secSpecificUnit"];
						$specModel->add($dataClothes);
// 						Log::write('sepc add' . $specModel->getLastSql());
					}
				}
				$i++;
			}
			if ($resultDetail)  {
				$order["id"] = implode(',',$resultOid);
				if($type == ORDER_TYPE_FORM){
					Output::instance()->object([
						'code'=>0,
						'msg'=>'提交成功',
						'oid'=>$order["id"]
					]);
					return;
				}
				if($noNeedJsonResult){
					Output::instance()->object($order);
				}else{
					return $order;
				}
			} else {
				if($noNeedJsonResult){
					Output::instance()->resultCode(code_sql_error);
				}else{
					return null;
				}
			}
		} else {
			if($noNeedJsonResult){
				Output::instance()->resultCode(code_sql_error);
			}else{
				return null;
			}
		}
	}

	public function getProTagName($id){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$TagListModel = M("module_product_tag_list");
		Session::switchCustomer($cid);
		$tagList = $TagListModel->alias('a')
			->join('inner join wx_module_product_tag b on a.tagId = b.id')
			->join("inner join wx_module_product_tag_group c on b.groupId=c.id")
			->where("a.pid=$id")
			->field('b.name,c.groupName')
			->select();
		$result = [];
		foreach($tagList as $index=>$tag){
			$result[] = $tag['groupName'].':'.$tag['name'];
		}
		return implode(',',$result);
	}

	public function curls($url, $timeout = '10')
	{
		// 1. 初始化
		$ch = curl_init();
		// 2. 设置选项，包括URL
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		// 3. 执行并获取HTML文档内容
		$info = curl_exec($ch);
		// 4. 释放curl句柄
		curl_close($ch);

		return $info;
	}
	private static function createIDSynthetic($oid,$IDPositive,$IDBack){
		$time=time();
		$fname="order_IDSynthetic".$oid.$time.".png";
		$fileName=LOCAL_PIC_PATH . "/$fname";
		$img = imagecreatetruecolor(640,1240);
		$color = imagecolorallocate($img,255,255,255);   //分配一个灰色
		imagefill($img,0,0,$color);

		$imgWidth=imagesx($img);
		$imgHeight=imagesy($img);
		$IDPositive=self::curls($IDPositive);
		$IDPositive=imagecreatefromstring($IDPositive);
		$positiveImgWidth=imagesx($IDPositive);
		$positiveImgHeight=imagesy($IDPositive);
		$positiveWidth = 600;
		$positiveHeight = $positiveWidth/$positiveImgWidth*$positiveImgHeight;
		if($positiveImgWidth>600){
			$positiveSmallImg = imagecreatetruecolor(600,$positiveHeight);
			$color = imagecolorallocate($positiveSmallImg,255,255,255);
			imagefill($positiveSmallImg,0,0,$color);
			imagecopyresampled($positiveSmallImg,$IDPositive,0,0,0,0,$positiveWidth,$positiveHeight,$positiveImgWidth,$positiveImgHeight);
			$IDPositive=$positiveSmallImg;
		}
		if($positiveHeight>$positiveWidth){
			$IDPositive = imagerotate($IDPositive, 90, 0);
		}
		$positiveImgWidth=imagesx($IDPositive);
		$positiveImgHeight=imagesy($IDPositive);
		$positiveWidth = 600;
		$positiveHeight = $positiveWidth/$positiveImgWidth*$positiveImgHeight;
		$positiveTop = $imgHeight/2-$positiveHeight-20;
		$positiveLeft = ($imgWidth-$positiveWidth)/2;
		imagecopyresampled($img,$IDPositive,$positiveLeft,$positiveTop,0,0,$positiveWidth,$positiveHeight,$positiveImgWidth,$positiveImgHeight);
		$IDBack=self::curls($IDBack);
		$IDBack=imagecreatefromstring($IDBack);
		$backImgWidth=imagesx($IDBack);
		$backImgHeight=imagesy($IDBack);
		$backWidth = 600;
		$backHeight = $backWidth/$backImgWidth*$backImgHeight;
		if($backImgHeight>600){
			$backSmallImg = imagecreatetruecolor(600,$backHeight);
			$color = imagecolorallocate($backSmallImg,255,255,255);
			imagefill($backSmallImg,0,0,$color);
			imagecopyresampled($backSmallImg,$IDBack,0,0,0,0,$backWidth,$backHeight,$backImgWidth,$backImgHeight);
			$IDBack=$backSmallImg;
		}
		if($backHeight>$backWidth){
			$IDBack= imagerotate($IDBack, 90, 0);
		}
		$backImgWidth=imagesx($IDBack);
		$backImgHeight=imagesy($IDBack);
		$backWidth = 600;
		$backHeight = $backWidth/$backImgWidth*$backImgHeight;
		$backTop = $imgHeight/2+20;
		$backLeft = ($imgWidth-$backWidth)/2;
		imagecopyresampled($img,$IDBack,$backLeft,$backTop,0,0,$backWidth,$backHeight,$backImgWidth,$backImgHeight);
		imagejpeg($img,$fileName);
		imagedestroy($img);
		imagedestroy($IDPositive);
		imagedestroy($IDBack);
		//开始上传
		if(file_exists($fileName)){
			$out=R("Upload/uploadLocalFileToOss",array($fname,$fileName));
			if(!$out->code){
				return $out->path;
			}
		}
	}
	/*
	 * 提交订单
	 * id : 订单id
	 * sid: 门店id，购物时选择的自提门店，没有对应门店信息时为-1
	 * price: 仅点菜模板有效
	 * remark: 购物者即用户的备注
	 * fullName: 用户姓名
	 * phone: 用户电话
	 * address: 收货地址
	 * orderTime: 仅点菜模板有效
	 * storeResourceId: 仅点菜模板有效
	 * storeResourceName: 仅点菜模板有效
	 * type: 非点菜模板为buy
	 * payType: 支付方式
	 * deliveryType: 配送方式
	 * userName: 微信openid
	 */
	public static function submitOrder($id, $sid, $price, $remark, $fullName, $phone,$province,$city, $country,$address, $orderTime,
		$storeResourceId, $storeResourceName, $type, $payType, $deliveryType, $userName, $invoiceTitle=NULL,
		$invoiceTitleName=NULL, $invoiceMethodName=NULL, $invoiceContentName=NULL,$IDName=null,$IDNumber=null,
		$IDPositive=null,$IDBack=null,$userCouponId=null,$joinQuan=null,$wxNumber=null,$purseMoney=0,$logisticsStatue=0,$verifyPhone='', $payPasswordToken = '',$bankNum = '', $customInfo = '') {
		$customerId = Session::$user['customerId'];
        $distriScheme = M('module_distribution_scheme');    // 查询配送方式及其对应的仓库
		Session::switchCustomer(0);
		$whereOrder["id"] = array("in",$id);

		$userPointModel = M('module_user_point');
		$OrderModel = M("module_product_order");
		$userCoupon = M("module_user_coupon");
		$detailModel = M("module_product_order_detail");
		Session::switchCustomer($customerId);
		$allUser = M("user");
		Session::switchCustomer(0);
		$order=$OrderModel->where($whereOrder)->field("*,sum(price) as totalPrice, sum(points) as totalPoints")->find();
		//Log::write('jie----pay-'.$payType.'-'.ORDER_PAYTYPE_WXPAY);

		//<侯佳2018-02-13添加，提交订单时积分不够的话不让提交>
		$userId = $order['uId'];
		$pointBalance = $userPointModel->where("cid = $customerId and userId = $userId")->getField('pointBalance');
		if (empty($pointBalance)) $pointBalance = 0;
		if (empty($order['totalPoints'])) $order['totalPoints'] = 0;
		if ($order['totalPoints'] > $pointBalance && $order['type'] == 'point') {
			Output::instance()->object([
				'code' => 2,
				'msg' => '积分余额不足'
			]);
			return;
		}

		//</侯佳2018-02-13添加，提交订单时积分不够的话不让提交>

		//<侯佳2018-03-29添加，积分订单扣除积分>
		if ($type == ORDER_TYPE_POINT) {
			$res = self::deductionPoint($id, $customerId);
			 if (!$res){
				Output::instance()->object([
					'code' => 1,
					'msg' => '提交失败'
				]);
				return;
			}

		}
		//</侯佳2018-03-29添加，积分订单扣除积分>

		if ($purseMoney) {
			$redis = new Redis();
			if ($redis->connect(C('REDIS_HOST'), C('REDIS_PORT'), C('REDIS_TIMEOUT')) == TRUE
				&& $redis->auth(C('REDIS_PASSWORD')) == TRUE
				&& $redis->select(C('REDIS_BASE_DB_INDEX')) == TRUE
			) {
				$redisToken = $redis->get('PayPasswordToken'.$id);
			}
			if ($payPasswordToken != $redisToken) {
				Output::instance()->object([
					'code' => 2,
					'msg' => 'token验证错误'
				]);
				return;
			}
		}
		if ($payType != ORDER_PAYTYPE_WXPAY && $payType != ORDER_PAYTYPE_TENPAY && $payType != ORDER_PAYTYPE_UPAY&& $payType != ORDER_PAYTYPE_DELIVERIY_PAY&&$payType != ORDER_PAYTYPE_ALIPAY&&$payType != ORDER_PAYTYPE_AINONGPAY) {
			if(floatval($order["totalPrice"]) >0 ) {
				$out=new stdClass();
				$out->code=1;
				$out->msg="错误的支付方式";
				Output::instance()->object($out);
				return;
			}
		}
		$IDSynthetic=null;
		if($order['proSource']==1){
			if(!$IDName||!$IDNumber||!$IDPositive||!$IDBack){
				$out=new stdClass();
				$out->code=1;
				$out->msg="收货信息不完整";
				Output::instance()->object($out);
				return;
			}else{
				$IDSynthetic = self::createIDSynthetic($id,$IDPositive,$IDBack);
			}
		}
		//判断优惠券
		if($userCouponId){
			$couponMoney=0;
			$userCouponIds = explode(",",$userCouponId);
			foreach($userCouponIds as $value){
				if(!$value){continue;}
				$couponInfo = $userCoupon->alias("a")
					->join("inner join wx_module_coupon b on a.couponId=b.id")
					->field("a.status,b.*")
					->where("a.id=$value")
					->find();
				$couponMoney+=$couponInfo['money'];
				if(!$couponInfo){
					$out=new stdClass();
					$out->code=1;
					$out->msg="优惠券不存在";
					Output::instance()->object($out);
					return;
				}
				if($couponInfo['status']==1){
					$out=new stdClass();
					$out->code=1;
					$out->msg="优惠券已使用";
					Output::instance()->object($out);
					return;
				}
				if($couponInfo['isEffective']==1){
					$nowTime = date("Y-m-d H:i:s");
					if($nowTime<$couponInfo['startTime']){
						$out=new stdClass();
						$out->code=1;
						$out->msg="优惠券未到使用期限";
						Output::instance()->object($out);
						return;
					}
					if($nowTime>$couponInfo['endTime']){
						$out=new stdClass();
						$out->code=1;
						$out->msg="优惠券已过期";
						Output::instance()->object($out);
						return;
					}
				}
			}
		}
		if($order['orderType']==6){
			$crowdInfo = $detailModel->alias("a")
				->join("inner join wx_module_product_order_detail_specification b on a.id= b.did")
				->join("inner join wx_module_product_specification c on c.pid = a.pid and c.firstSpecificName=b.firstSpecificName and c.secSpecificName=b.secSpecificName")
				->join("inner join wx_module_product_crowdfunding d on c.firstSpecificId=d.specId and d.pid=a.pid")
				->join("inner join wx_module_product e on a.pid = e.id")
				->field("e.crowdStatus,d.*,a.count")
				->where("a.oid=$id")
				->find();
			if($crowdInfo['crowdStatus']>=2){
				Output::instance()->resultCode(1,"众筹已结束！");
				return;
			}
			if($crowdInfo['restrictAmount']&&$crowdInfo['surplusAmount']<$crowdInfo['count']){
				Output::instance()->resultCode(1,"份数不足！");
				return;
			}
			if($crowdInfo['restrictPerson']&&$crowdInfo['surplusPerson']<=0){
				Output::instance()->resultCode(1,"限购以满！");
				return;
			}
			if($crowdInfo['restrictAmount']&&$crowdInfo['surplusAmount']<=0){
				Output::instance()->resultCode(1,"限购以满！");
				return;
			}
		}
		// else {
		// 	//$result = $OrderModel->where($whereOrder)->save($data);
		// }
		if (isset($id) ) {
			if($order['orderType'] == ORDER_ORDERTYPE_NINE){
				//表单不进行库存的增减
			}else{
				if ($type != ORDER_TYPE_POINT) {
					$verifyPrice = self::verifyPrice($id);
					if(!$verifyPrice){
						Output::instance()->resultCode(code_product_no_inventory, "商品价格有变动，请重新选择商品下单");
						return;
					}
				}

				$orderStatus = self::verifySubmitOrder($id, $sid, $userName, $type);
				if ($orderStatus["isSubmitted"]) {
					Output::instance()->resultCode(code_product_order_submitted);
					return;
				}
				if($orderStatus["inventory"]["isRemoved"]){
					$detail = '['. $orderStatus["inventory"]["name"];
					if ($orderStatus["inventory"]["spec"] != "" ) {
						$detail .= '-规格:' . $orderStatus["inventory"]["spec"];
					}
					$detail .= ']已下架';
					Output::instance()->resultCode(code_product_no_inventory, $detail);
					return;
				}
				if($orderStatus["inventory"]["selfBuyCount"]){
					$detail = '超出个人购买最大数量';
					Output::instance()->resultCode(code_product_no_inventory, $detail);
					return;
				}
				if (!$orderStatus["inventory"]["result"]) {
					$detail = '['. $orderStatus["inventory"]["name"];
					if ($orderStatus["inventory"]["spec"] != "" ) {
						$detail .= '-规格:' . $orderStatus["inventory"]["spec"];
					}
					$detail .= ']库存不足，不能购买';
					Output::instance()->resultCode(code_product_no_inventory, $detail);
					return;
				}
				if (!$orderStatus["isPaytypeValid"]) {
					Output::instance()->resultCode(code_product_pay_type);
					return;
				}
				$needDeductInventory = $orderStatus["needDeductInventory"];
			}
		} else {
			$inventory = self::verifySubmitOrderProductInventory(0, $sid, $userName, $type);

			if ($inventory == false) {
				Output::instance()->resultCode(code_product_no_inventory);
				return;
			}
			$needDeductInventory = true;
		}
		 if ($deliveryType == ORDER_DELIVERYTYPE_PICKUP&&isset($sid) && $sid != -1) {
		 	$StoreModel = M("store");
		 	$whereStore['id'] = $sid;
		 	$store = $StoreModel->where($whereStore)->find();
		 	if ($store == false) {
		 		Output::instance()->resultCode(code_store_not_exist);
		 		return;
		 	}
			 $data["storeResourceId"] = $sid;
			 $data["storeResourceName"] = $store["name"];
			 $data["channelId"] = $store["vId"];
		 }
		if (isset($deliveryType)) {
			if ($deliveryType == ORDER_DELIVERYTYPE_PICKUP) {
				if (isset($store) && $store["isPickup"] == 1) {
					Output::instance()->resultCode(code_store_pickup_not_set);
					return;
				}
				if (isset($payType) && (strcasecmp($payType, ORDER_PAYTYPE_TRANSFER) == 0)) {
					$data["status"] = ORDER_STATUS_PAYING;
				} else {
					$data["status"] = order_status_deliveringtostore;
				}
			} else if (strstr($deliveryType, 'delivery') == $deliveryType) {
				if (isset($payType) && (strcasecmp($payType, ORDER_PAYTYPE_TRANSFER) == 0)) {
					$data["status"] = ORDER_STATUS_PAYING;
				}else if($order["isTeam"]!=1){
					$data["status"] = order_status_delivering;
				}else{
					$data["status"]='teaming';
				}
                $deliveryType = 'delivery';
				//$data["logisticsId"] = $logistics["id"];
				//$data["costName"] = $logistics["costName"];
			} else {
				Output::instance()->resultCode(code_product_delivery_type);
				return;
			}
			if($order["isActivity"]==1){
				$data["status"] = order_status_ordersign;  //已参与
			}

			if(!$logisticsStatue){
				$data["deliveryType"] = $deliveryType;
			}
            // TODO: 如果是物流配送更改添加上仓库
            if ($data["deliveryType"] == ORDER_DELIVERYTYPE_DELIVERY) {
                // 先简单在此处直接使用第一个仓库, 当扩充多仓库时, 应当在updateSubmitOrderData方法中标记处根据地址来选择仓库
                // 查询出仓库ids
                $distriSchemeWhere['distriScheme.id'] = array('eq', $order['distributionId']);
                $distriSchemeWhere['distriDepot.cid'] = array('eq', $customerId);
                $depotIds = $distriScheme
                    ->alias('distriScheme')
                    ->join('wx_module_distribution_depot distriDepot on distriScheme.id = distriDepot.distributionId')
                    ->where($distriSchemeWhere)
                    ->field('depotId')
                    ->select();

                // 增加仓库id   这里先使用第一个(下标0的缘故)仓库(原因看上处注释)
                // 存在仓库
                if (count($depotIds) > 0) {
                    $data['depotid'] = $depotIds[0]['depotId'];
                }
            } elseif ($data["deliveryType"] == ORDER_DELIVERYTYPE_PICKUP) {//生成门店自提码
				do {
					$str = time() * rand(1, 9);
					$data['pickupCode'] = substr($str, -8);
					$isHaveWhere['pickupCode'] = ['eq', $data['pickupCode']];
					$isHaveWhere['status'] = ['neq', 'ok'];
					$isHave = $OrderModel->where($isHaveWhere)->find();
				} while ($isHave);
			}
		}
		if (isset($payType)) {
			$data["payType"] = $payType;
			$productList = self::getSubmitOrderProduct($id, $order['orderType']);
//			$pay = self::getProductPay($productList, NULL, $id);
//
//			if (!isset($pay)) {
//				return;
//			}
            if (isset($id)) {
                $productFee = $order["totalPrice"];
                // if($order["freebuy"]!="1") {
                // 	if (floatval($productFee) > 0 && (floatval($productFee)-floatval($pay["price"])) ==0) {
                //            Output::instance()->resultCode(code_product_changed_pay_invalid);
                //            return;
                //        }
                // }
            }
            /*else {
		        $productFee = $pay["price"];
		    }*/
            Session::switchCustomer($customerId);
            if($order["freebuy"]=="1") { //自由购商品
				$price=self::getOrderDetailPrice($id);
				$logistics = R("Mall/getDeliveryCost", array($price, NULL, $customerId,$order['distributionId']));
			} else {
				//获取运费
				$logistics = R("Mall/getDeliveryCost", array($productFee, NULL, $customerId,$order['distributionId']));
			}
            Session::switchCustomer(0);

			if (isset($logistics["cost"])&&$deliveryType=="delivery") {
				$transportFee = $logistics["cost"];
			} else {
				$transportFee = 0;
			}
			$price =  $productFee + $transportFee;
			if($price > 0){
				if ($payType == ORDER_PAYTYPE_WXPAY || $payType == ORDER_PAYTYPE_TENPAY|| $payType == ORDER_PAYTYPE_ALIPAY
	                || $payType == ORDER_PAYTYPE_UPAY || $payType == ORDER_PAYTYPE_AINONGPAY) {
					if (isset($data["status"])) {
						$data["status"] = ORDER_STATUS_PAYING;
					}
					// total fee not update here, update when wxpay submit success
					if(!isset($id) || !strstr($id, ',')){
						$data["price"] = $productFee;
						if (isset($logistics["cost"])) {
							$data["logisticsCost"] = $logistics["cost"];
						}
					}
				} else {
					if(!strstr($id, ',')){
						$data["price"] = $price;
						if (isset($logistics["cost"])) {
							$data["logisticsCost"] = $logistics["cost"];
						}
					}
				}
			}
		}
		$createTime = date("Y-m-d H:i:s");
		if($joinQuan){
			$uid = $order['uId'];
			$qid = $order['qId'];
			$quanInfo=M("quan_user")->where("qid=$qid and uid = $uid and deleted=0")->find();
			if($quanInfo){
				Output::instance()->resultCode(1,"已加入！");
				return;
			}
			$allUserData['fullName']=$fullName;
			$allUserData['phone']=$phone;
			$allUserData['wxNumber']=$wxNumber;
			//mh增加手机号验证，20180127
			if ($verifyPhone){
				$phone_params = new StdClass();
                $phone_params->phone = $verifyPhone;
                Module::callModule('phone', NULL, 'verifyPhone', $phone_params);
                $allUserData['phone']=$verifyPhone;
			}
            $allUserData['customInfo'] = $customInfo;
			$allUser->where("id=$uid")->save($allUserData);
			$data['orderType']=4;//标记为加入合伙人订单
		}
		if (!isset($data["price"])) {
			$data["price"] = 0;
		}
		$data["storeId"] = $sid;
		if(!$logisticsStatue){
			$data["fullName"] = $fullName;
			$data["phone"] = $phone;
		}
        if ($data["deliveryType"] == 'delivery') {
            $data["address"] = $address;
			$data["province"] = $province;
			$data["city"] = $city;
			$data["country"] = $country;
        }
		$data['IDName'] = $IDName;
		$data['IDNumber'] = $IDNumber;
		$data["remark"] = $remark;
		$data["orderTime"] = $orderTime;
		$data["createTime"] = $createTime;
		$data["updateTime"] = $createTime;
		$data['IDPositive'] = $IDPositive;
		$data['IDBack'] = $IDBack;
		$data['IDSynthetic']=$IDSynthetic;
//		if(isset($pay['levelId']) && isset($pay['levelName'])){
//			$data['levelId'] = $pay['levelId'];
//			$data['levelName'] = $pay['levelName'];
//		}
		$data['invoiceTitle'] = $invoiceTitle;
		$data['invoiceTitleName'] = $invoiceTitleName;
		$data['invoiceMethodName'] = $invoiceMethodName;
		$data['invoiceContentName'] = $invoiceContentName;
		$sn = self::createOrderSerialNumber($id, $customerId);
		$data["tempSerialNumber"]=$sn;
		if (!isset($id)) {
			$data["fromUserName"] = $userName;
			$data["fromCustomerId"] = $customerId;
			$data["price"] = $price;
			$data["type"] = $type;
			$OrderModel = M("module_product_order");
			$result = $OrderModel->add($data);

		} else {
			if (!strstr($id , ',') || !isset($logistics)||$deliveryType!="delivery") {
				$result = self::updateSubmitOrderData($id, $data,$customerId,$userCouponId,$purseMoney);
			} else {
				$result = self::updateSubmitOrderData($id, $data, $customerId,$userCouponId,$purseMoney,$payType, $logistics);
			}
		}

		if ($result !== false) {
			if (!isset($id)) {
				$id = $result;
				self::moveProductFromCartToOrder($id, $userName, $type);
			} else if($order['orderType'] == ORDER_ORDERTYPE_NINE){
				//表单订单,不对购物车进行处理
			}else{
				$cartPids = '';
				foreach ($productList as $product) {
					$cartPids .= $product["id"] . ',';
				}
				if (count($productList) > 0) {
					$cartPids = substr($cartPids, 0, strlen($cartPids) - 1);
				}
				self::moveProductFromCartToOrder(-1, $userName, $type, $cartPids);
			}

			if (($needDeductInventory&&$payType !== ORDER_PAYTYPE_ALIPAY&&$payType !== ORDER_PAYTYPE_AINONGPAY&&!isNativeApp())|| ($needDeductInventory&&$type == ORDER_TYPE_POINT)) {
				// 一键支付的等待付款状态的商品库存已被扣
				R('Product/deductProductInventory', array($id));
			}

			if (!isset($payType) || (isset($payType) && $payType !== ORDER_PAYTYPE_UPAY &&
					$payType !== ORDER_PAYTYPE_WXPAY && $payType !== ORDER_PAYTYPE_TENPAY &&$payType !== ORDER_PAYTYPE_ALIPAY &&$payType !== ORDER_PAYTYPE_AINONGPAY)) {
				// 一键支付和微信支付支付成功才扣减库存
				R('Product/addProductSalesCount', array($id));
			}
			if($userCouponId){
				$productFee=round($productFee-$couponMoney,2);
                $productFee<0?$productFee=0:"";
				$price = round($price-$couponMoney,2);
                $price<0?$price=0:"";
			}
			if($purseMoney){
				$productFee=round($productFee - $purseMoney,2);
			    $price = round($price -$purseMoney,2);
            }
			if (isset($payType) && ($payType == ORDER_PAYTYPE_WXPAY || $payType == ORDER_PAYTYPE_TENPAY || $payType == ORDER_PAYTYPE_UPAY || $payType == ORDER_PAYTYPE_ALIPAY  || $payType == ORDER_PAYTYPE_AINONGPAY)) {
				if (count($productList) == 1) {
					$desc = $productList[0]["name"];
				} else {
					$desc = count($productList) . '项商品';
				}
				$desc = str_replace(" ", "", $desc);
				if($price>0){
					//付款$productFee 订单金额 $transportFee运费
					if ($payType == ORDER_PAYTYPE_WXPAY) {
						if(isMicroMessengerUserAgent()){
							//判断是否是微信浏览器，微信浏览器的话支付方式和之前一样无变化
				            R('Wxpay/getWxPayParam', array($sn, $desc, $productFee,
								$transportFee, $userName));
				        }else if (isNativeApp()){
							//判断是否是app，app的话使用H5支付方式，场景信息为app信息安卓移动应用{"h5_info": {"type":"Android","app_name": "王者荣耀","package_name": "com.tencent.tmgp.sgame"}}
							$scene['h5_info']['type'] = 'Android';
							$scene['h5_info']['app_name'] = '易小康';
							$scene['h5_info']['package_name'] = 'package_name';
							$scene_info = json_encode($scene);
				            R('Wxpay/getWxPayParam', array($sn, $desc, $productFee,
								$transportFee, $userName,'','','',TRADE_TYPE_MWEB,$scene_info));
				        }else{
							//其他场景按照WAP网站应用场景进行处理。//WAP网站应用{"h5_info": {"type":"Wap","wap_url": "https://pay.qq.com","wap_name": "腾讯充值"}}
							$scene['h5_info']['type'] = 'Wap';
							$scene['h5_info']['wap_url'] = C('SERVER_NAME');
							$scene['h5_info']['wap_name'] = '摩宝时代';
							$scene_info = json_encode($scene);
				            R('Wxpay/getWxPayParam', array($sn, $desc, $productFee,
								$transportFee, $userName,'','','',TRADE_TYPE_MWEB,$scene_info));
				        }
					} else {
						$retUrl = C('SERVER_HOST'). "call.html?customerId=" . $customerId  . '&userName=' . $userName .'&module=product&method=orderSuccess&params=%7B%22id%22:' .$id . '%7D';
						if($order["orderType"]==3){
							$retUrl = C('SERVER_HOST'). "call.html?customerId=" . $customerId  . '&userName=' . $userName .'&module=allChips&method=indianaSuccess&params=%7B%22parId%22:' .$order["playOrderId"] . '%7D';
						}
						if ($payType == ORDER_PAYTYPE_TENPAY) {
							R('Tenpay/submitTenpay', array($sn, $price, $desc, $retUrl));
						} else if ($payType == ORDER_PAYTYPE_UPAY ) {
							R('Upay/submitUpay', array($sn, $price, $desc, $retUrl));
						}else if($payType == ORDER_PAYTYPE_ALIPAY){
							$p=new stdClass();
							$url =  C('SERVER_HOST')."Alipay/submitPay.json?cid=$customerId&sn=$sn&desc=$desc&totalFee=$price&returnUrl=$retUrl";
							$p->url=$url;
							Output::instance()->object($p);
						}else if($payType == ORDER_PAYTYPE_AINONGPAY){
							if(empty($bankNum)){
								Output::instance()->resultCode(1,"请输入支付的银行卡卡号！");
								return;
							}
							$redis = new RedisAPI();
							$redis->set($sn, $bankNum, 15*60);
							R('AiNongpay/submitAiNongPay', array($sn, $price, $desc, $retUrl,$customerId,'',$bankNum));
						}
					}
				}else if($productFee<=0){
				    $order['price']=$productFee;
					ProductOrder::updateOrderDone($customerId,$id,'');
					Output::instance()->object($order);
				}

			} else {
				$resultDone["id"] = $id;
				$resultDone["price"] = $price;
				$resultDone["payType"] = $payType;
				$p=new stdClass();
				$p->id=$id;
				$p->userName=$userName;
				Output::instance()->object($resultDone);
			}
			Session::switchCustomer($customerId);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
		if ($res) {
			$param = new stdClass();
			$param->userName = $userName;
			$param->id = $id;
			$param->type = $type;
			self::SendorderNotice($param);
			self::SendQuanOrderNotice($param);
		}

	}
	//商品编号使用客户id + 时间 + id后三位
	private static function createOrderSerialNumber($ids, $customerId) {
		if (!strstr($ids, ',')) {
			$id = $ids;
		} else {
			// 如果拆单则使用第一个订单的id
			$id = substr($ids,0,strpos($ids,','));
		}

		$length = strlen($id);
		if ($length >= 3) {
			$id = substr($id, -3);
		} else {
			$id = str_pad($id, 3, '0', STR_PAD_LEFT);
		}
		$sn = $customerId . date("ymdHis") . $id;
		return $sn;
	}



	private static function updateSubmitOrderData($ids, $data, $customerId,$userCouponId,$purseMoney,$payType = NULL, $logistics = NULL) {
		$idArray = explode(',', $ids);
		$userCouponIds = explode(',', $userCouponId);
        $purseMoneys = explode(',', $purseMoney);
		$data['remark']=json_decode($data['remark'],true);
		$OrderModel = M("module_product_order");
		$userCoupon = M("module_user_coupon");
		$detailModel = M("module_product_order_detail");
		$couponWhere['a.id']=array("in",$userCouponIds);
		$couponInfo = $userCoupon->alias("a")
			->join("inner join wx_module_coupon b on a.couponId=b.id")
			->field("b.name,b.money")
			->where($couponWhere)
			->select();
		if (count($idArray) > 1) {
			unset($data["points"]);
			unset($data["logisticsPoints"]);
			unset($data["price"]);
			unset($data["logisticsCost"]);
			foreach ($idArray as $key=>$id) {
                $whereOrder["id"] = $id;
				$data['remark']=$data['remark'][$id];
				$data["serialNumber"] = self::createOrderSerialNumber($id,$customerId);
				$data['userCouponId']=$userCouponIds[$key];
				$data['couponName']=$couponInfo[$key]['name'];
				$data['couponMoney']=$couponInfo[$key]['money'];
				$data['ppat']=$detailModel->where("oid=$id")->sum("ppat");
				if($purseMoney>0){
				    $orderInfo = $OrderModel->where($whereOrder)->field("price,couponMoney,userCouponId")->find();
                    $orderInfo['userCouponId']?$price = $orderInfo['price']-$orderInfo['couponMoney']:$price = $orderInfo['price'];
                    if($purseMoney>$price){
                        $purseMoney-=$price;
                        $data['purseMoney']=$price;
                    }else{
                        $data['purseMoney']=$purseMoney;
                    }
                }
//                $data['purseMoney']=$purseMoneys[$key];
                // TODO: 多仓库地址方式选择逻辑
				$result = $OrderModel->where($whereOrder)->save($data);
			}

		} else {
			$whereOrder["id"] = $ids;
			$data['remark']=$data['remark'][$ids];
			$data['userCouponId']=$userCouponId;
			$data['couponName']=$couponInfo[0]['name'];
			$data['couponMoney']=$couponInfo[0]['money'];
            $data['purseMoney']=$purseMoney;
			$data['ppat']=$detailModel->where("oid=$ids")->sum("ppat");
			$data["serialNumber"] = self::createOrderSerialNumber($ids,$customerId);
            // TODO: 多仓库地址方式选择逻辑
			$result = $OrderModel->where($whereOrder)->save($data);
		}
		if ($logistics) {
			$arrLogisticsCost = explode(',', $logistics["strCost"]);
			$arrLogisticsPoints = explode(',', $logistics["strPoints"]);
			foreach ($idArray as $k => $id) {
				$whereTmp["id"] = intval($id);
				$tmpPrice = floatval($OrderModel->where($whereTmp)->getField('price'));
				if ($payType != ORDER_PAYTYPE_WXPAY && $payType != ORDER_PAYTYPE_TENPAY && $payType != ORDER_PAYTYPE_UPAY
						&& $arrLogisticsCost[$k]) {
					$tmpdata["price"] = $arrLogisticsCost[$k] + $tmpPrice;
				} else {
					$tmpdata["price"] = $tmpPrice;
				}
				$tmpdata["logisticsCost"] = $arrLogisticsCost[$k];
				$OrderModel->where($whereTmp)->save($tmpdata);
			}
		}
		return $result;
	}

	// 将购物车中的商品移出
	private static function moveProductFromCartToOrder($cartOid, $userName, $type, $pids = NULL) {
		$conditionDetail["oid"] = 0;
		$conditionDetail["fromUserName"] = $userName;
		$conditionDetail["type"] = $type;
		$customerId = Session::$user["customerId"];
		if ($pids) {
			$pdtArr = explode(',', $pids);
			if (count($pdtArr) > 1) {
				$whereArray = array();
				foreach ($pdtArr as $id) {
					array_push($whereArray, array('eq', intval($id)));
				}
				array_push($whereArray, 'OR');
				$conditionDetail["pid"] = $whereArray;
			} else {
				$conditionDetail["pid"] = $pids;
			}
		}
		Session::switchCustomer(0);
		$DetailModel = M("module_product_order_detail");
		Session::switchCustomer($customerId);
		$DetailModel->where($conditionDetail)->delete();
	}

	public static function cancelWxOrder($oid) {
		R('Product/revertProductInventory', array($oid));
		Output::instance()->resultCode();
	}

	private static function verifySubmitOrder($ids, $sid, $userName, $type) {
		$OrderModel = M("module_product_order");

		$isSubmitted = false;
		$inventory["result"] = true;
		$isPaytypeValid = true;

		$idArray = explode(',', $ids);
		if (count($idArray) > 1) {
			$whereArray = array();
			foreach ($idArray as $id) {
				array_push($whereArray, array('eq', intval($id)));
			}
			array_push($whereArray, 'OR');
			$where["id"] = $whereArray;

			$order = $OrderModel->where($where)->select();
			$orderPayType = NULL;
			foreach($order as $k => $v){
				$status = $v['status'];
				if ($status != NULL && $status !== order_status_notsubmit && $status !== ORDER_STATUS_PAYING)  {
					$isSubmitted = true;
					break;
				}
				if ($orderPayType != NULL) {
					if ($orderPayType != $v['payType']) {
						$isPaytypeValid = false;
						break;
					} else {
						$orderPayType = $v['payType'];
					}
				}
			}

			if (isset($order) && ($orderPayType != NULL) &&
					($orderPayType == ORDER_PAYTYPE_UPAY || $orderPayType == ORDER_PAYTYPE_TENPAY) &&
                    $status == ORDER_STATUS_PAYING ) {
				// 一键支付和财付通支付的订单库存已经扣减
				$needDeductInventory = false;
			} else {
				$needDeductInventory = true;
				foreach ($idArray as $id) {
					$inventory = self::verifySubmitOrderProductInventory($id, $sid, $userName, $type);
					if ($inventory["result"] == false) {
						break;
					}
				}
			}
		} else {
			$where["id"] = $ids;
			$order = $OrderModel->where($where)->find();
			if ($order["status"] != NULL && $order["status"] !== order_status_notsubmit
					&& $order["status"] !== ORDER_STATUS_PAYING)  {
				$isSubmitted = true;
			}

			if (isset($order) && ($order["payType"] != NULL) &&
					(($order["payType"] == ORDER_PAYTYPE_UPAY) && $order["status"] == ORDER_STATUS_PAYING)) {
				// 一键支付的订单库存已经扣减
				$needDeductInventory = false;
			}
			else {
				//表单订单会走
				$needDeductInventory = true;
				$inventory = self::verifySubmitOrderProductInventory($ids, $sid, $userName, $type);
			}
		}

		$result["isSubmitted"] = $isSubmitted;
		$result["isPaytypeValid"] = $isPaytypeValid;
		$result["inventory"] = $inventory;
		$result["needDeductInventory"] = $needDeductInventory;
		return $result;
	}
	private static function verifyPrice($oid){
		$detailModule = M("module_product_order_detail");
		$productModule = M("module_product");
		$detailList = $detailModule->alias("a")
			->join("wx_module_product_order_detail_specification b on a.id=b.did")
			->field("b.id,a.pid,a.price,a.playType,b.firstSpecificName,b.secSpecificName")
			->where("a.oid in ($oid)")
			->select();
		foreach($detailList as $key=>$value){
			if($value['id']){
				$where = NULL;
				$where['b.pid']=array("eq",$value['pid']);
				$where['b.firstSpecificName']=array("eq",$value['firstSpecificName']);
				$value['secSpecificName']?$where['b.secSpecificName']=array("eq",$value['secSpecificName']):"";
				$productInfo = $productModule->alias("a")
					->join("inner join wx_module_product_specification b on a.id=b.pid")
					->where($where)
					->field("a.teamPrice,a.perMoney,b.miPrice,b.discountedPrice,b.fixedPrice,b.seckillPrice")
					->find();
			}else{
				$productInfo = $productModule->where("id=".$value['pid'])->field("teamPrice,perMoney,miPrice,discountedPrice,fixedPrice,seckillPrice")->find();
			}
			if(!$productInfo){
				return false;
			}
			switch($value['playType']){
				case 'team':
					if($productInfo['teamPrice']!=$value['price']){
						return false;
					}
					break;
				case 'indiana':
					if($productInfo['perMoney']!=$value['price']){
						return false;
					}
					break;
				case 'miPrice':
					if($productInfo['miPrice']!=$value['price']){
						return false;
					}
					break;
				case 'discounted':
					if($productInfo['discountedPrice']!=$value['price']){
						return false;
					}
					break;
				case 'fixed':
					if($productInfo['fixedPrice']!=$value['price']){
					return false;
				}
					break;
				case 'seckillPrice':
					if($productInfo['seckillPrice']!=$value['price']){
						return false;
					}
					break;
			}
		}
		return true;
	}
	private static function verifySubmitOrderProductInventory($oid, $sid, $userName, $type) {
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$DetailModel = M("module_product_order_detail");
		$orderModel = M("module_product_order");
		$numberModel = M("module_mill_number");
		$ProductModel = M("module_product");
		Session::switchCustomer($customerId);
		if (isset($oid)) {
			$arrDetail = $DetailModel->where("oid in ($oid)")->select();
			if(strstr($oid,',')){
				$clothesWhere['dt.oid'] = array('in', $oid);
			}else{
				$clothesWhere['dt.oid'] =  $oid;
			}

			$arrClothes = $DetailModel->alias("dt")->join("RIGHT JOIN wx_module_product_order_detail_specification dc ON dc.did = dt.id")
				->where($clothesWhere)->select();
		} else {
			$conditionDetail["storeId"] = $sid;
			$conditionDetail["oid"] = 0;
			$conditionDetail["fromUserName"] = $userName;
			$conditionDetail["type"] = $type;
			$arrDetail = $DetailModel->where($conditionDetail)->select();
		}

		foreach ($arrDetail as $detail) {
			$isSpec = true;
			ob_start();
			R("ApplePie/synchroStock",array($detail['pid'],true));
			ob_end_clean();
			$ProductInfo = $ProductModel->where("id=".$detail['pid'])->find();
			foreach ($arrClothes as $detailClothes) {
				if ($detailClothes["pid"] == $detail["pid"]) {
					$isSpec = false;
					$where["pdt.id"] = $detail["pid"];
					if($ProductInfo['isChainPro']){
						$where["pdt.id"] = $ProductInfo["supplyProId"];
					}
					$where["sepc.firstSpecificName"] = $detailClothes["firstSpecificName"];
					if (!empty($detailClothes["secSpecificName"])) {
						$where["sepc.secSpecificName"] = $detailClothes["secSpecificName"];
					}
					if($ProductInfo['playType']==4){
						$preCount = 0;
						$json = json_decode($ProductInfo['json'],true);
						if(strtotime($json['seckillStartTime'])<time()&&strtotime($json['seckillEndTime'])>time()){
						    $where["pdt.id"] = $detail["pid"];
							$seckillSpecPreSalceCount = json_decode($json['seckillSpecPreSalceCount'],true);
							foreach($seckillSpecPreSalceCount as $item) {
								if($item['count']&&$item['firstname']==$detailClothes["firstSpecificName"]&&$item['secondname']==$detailClothes["secSpecificName"]){
									$preCount = $item['count'];
								}
							}
							$where["sepc.seckillInventoryCount"] = array("lt", intval($detailClothes["count"])+intval($preCount));
						}else{
							$where["pdt.inventory"] = 1;
							$where["sepc.inventoryCount"] = array("lt", intval($detailClothes["count"]));
						}
					}else{
						$where["pdt.inventory"] = 1;
						$where["sepc.inventoryCount"] = array("lt", intval($detailClothes["count"]));
					}
					$inventory = $ProductModel->alias("pdt")
						->join("wx_module_product_specification sepc ON sepc.pid = pdt.id")
						->join("wx_module_product_order_detail detail ON detail.pid = pdt.id")
						->where($where)->find();

					if ($inventory !== null) {
						$result["name"] = $inventory["name"];
						if (!empty($detailClothes["firstSpecificName"]) && !empty($detailClothes["secSpecificName"])) {
							$result["spec"] = $detailClothes["firstSpecificName"] . ' ' . $detailClothes["secSpecificName"];
						} else if (!empty($detailClothes["firstSpecificName"])) {
							$result["spec"] = $detailClothes["firstSpecificName"];
						} else {
							$result["spec"] = $detailClothes["secSpecificName"];
						}
						$result["result"] = false;
						return $result;
					}
				}
			}
			if ($isSpec) {
				$whereP["pdt.id"] = $detail["pid"];
				if($ProductInfo['isChainPro']){
					$whereP["pdt.id"] = $ProductInfo["supplyProId"];
				}
				if($ProductInfo['playType']==4){
					$json = json_decode($ProductInfo['json'],true);
					if(strtotime($json['seckillStartTime'])<time()&&strtotime($json['seckillEndTime'])>time()){
				        $whereP["pdt.id"] =$detail["pid"];
						$json['seckillPreSalceCount']?$preCount = $json['seckillPreSalceCount']:$preCount=0;
						$whereP["pdt.seckillInventoryCount"] = array("lt", intval($detail["count"])+intval($preCount));
					}else{
				         	$whereP["pdt.inventory"] = 1;
						$whereP["pdt.inventoryCount"] = array("lt", intval($detail["count"]));
					}
				}else{
				    $whereP["pdt.inventory"] = 1;
					$whereP["pdt.inventoryCount"] = array("lt", intval($detail["count"]));
				}
				$inventory = $ProductModel->alias("pdt")->join("wx_module_product_order_detail detail ON detail.pid = pdt.id")->where($whereP)->find();
				Log::write("秒杀提交判断库存  ".$ProductModel->getLastSql());
				if ($inventory !== null&&$inventory["playType"]!=3) {
					$result["name"] = $ProductInfo["name"];
					$result["spec"] = "";
					$result["result"] = false;
					return $result;
				}
				$inventory = $orderModel->where("id=".$oid)->find();
				if($inventory["orderType"]==3){
					$inventory = $orderModel->alias("a")
						->join("inner join wx_module_mill_par b on a.playOrderId = b.id")
						->join("inner join wx_module_mill_period c on b.perId = c.id")
						->join("inner join wx_module_product d on c.pid=d.id")
						->where("a.id in ($oid) and b.perId is not NULL")
						->field("a.*,b.perId,b.count,d.maxCopies")
						->find();
					//判断是否超出最大限购数量
					$joinCount = $numberModel
						->where("perId=".$inventory["perId"]." and openId='".$userName."'")
						->count();
					if($inventory["maxCopies"]&&$joinCount+$inventory["count"]>$inventory["maxCopies"]){
						$result["name"] = $inventory["name"];
						$result["spec"] = "";
						$result["result"] = false;
						$result["selfBuyCount"] = true;
						return $result;
					}
					$inventory = $DetailModel->alias("a")
						->join("inner join wx_module_product_order b on a.oid = b.id")
						->join("inner join wx_module_mill_par c on b.playOrderId = c.id")
						->join("inner join wx_module_mill_period d on c.perId = d.id")
						->join("inner join wx_module_product e on e.id = a.pid")
						->field("e.name")
						->where("d.surplus < c.count and a.oid in ($oid)")
						->find();
					Log::write("付款前判断库存--".$DetailModel->getLastSql());
					if ($inventory !== null) {
						$result["name"] = $inventory["name"];
						$result["spec"] = "";
						$result["result"] = false;
						return $result;
					}
				}
				if($ProductInfo['playType']==4){
					$json = json_decode($ProductInfo["json"],true);
					$seckillStartTime = strtotime($json["seckillStartTime"]);
					$seckillPreEndTime = $json['seckillPreEndTime'];
					if($seckillPreEndTime){
						$newTime = time();
						$seckillEndtime = $seckillStartTime+$seckillPreEndTime;
						if($newTime>$seckillEndtime){
							$result["name"] = $ProductInfo["name"];
							$result["spec"] = "";
							$result["result"] = false;
							return $result;
						}
					}
				}
			}
			$proInfo = $ProductModel->where("id=".$detail["pid"])->find();
			if($proInfo["isRemoved"]){
				$result["isRemoved"]=true;
				return $result;
			}
		}
		$result["result"] = true;
		$result["isRemoved"]=false;
		$result["selfBuyCount"] = false;
		return $result;
	}



	private static function deductMemberPoint($userName, $customerId, $userName, $payType, $points, $productList) {
		$member = R('Member/getMember', array($userName));

// 		Session::switchCustomer($customerId);
		if (!$member) {
			Output::instance()->resultCode(code_member_invalid);
			return false;
		} else {
			$interactScore = 0;
			$consumeScore = 0;
			$storedValue = 0;
			if ($payType == ORDER_PAYTYPE_INTERACT) {
				if ($member["interactScore"] < $points) {
					Output::instance()->resultCode(code_member_points_not_enough);
					return false;
				}
				$interactScore = 0 - $points;
			} else if ($payType == ORDER_PAYTYPE_CONSUME) {
				if ($member["consumeScore"] < $points) {
					Output::instance()->resultCode(code_member_points_not_enough);
					return false;
				}
				$consumeScore = 0 - $points;
			}
		}
		$detail = '';
		foreach ($productList as $product) {
			$detail = $detail . $product["name"] . ',' ;
		}
		if (count($productList) > 0) {
			$detail = substr($detail, 0, strlen($detail) - 1);
		}
		R('Member/addMemberScoreDetail', array($userName,$member["id"], $payType,
			$interactScore, $consumeScore, $storedValue,
			NULL, source_member_points, $detail));
// 		Session::switchCustomer(0);
		return true;
	}

	private static function deductMemberStoredPrice($userName, $customerId, $userName, $payType, $price, $productList) {
		$member = R('Member/getMember', array($userName));
// 		Session::switchCustomer($customerId);
		if (!$member) {
			Output::instance()->resultCode(code_member_invalid);
			return false;
		} else {
			$interactScore = 0;
			$consumeScore = 0;
			$storedValue = 0;
			if ($payType == 'stored') {
				if ($member["storedValue"] < $price) {
					Output::instance()->resultCode(code_member_stored_not_enough);
					return false;
				}
				$storedValue = 0 - $price;
			} else {
				Output::instance()->resultCode(code_system_error);
				return  false;
			}
		}
		$detail = '';
		foreach ($productList as $product) {
			$detail = $detail . $product["name"] . ',' ;
		}
		if (count($productList) > 0) {
			$detail = substr($detail, 0, strlen($detail) - 1);
		}
		R('Member/addMemberScoreDetail', array($userName,$member["id"], $payType,
			$interactScore, $consumeScore, $storedValue,
			NULL, source_member_points, $detail));
// 		Session::switchCustomer(0);
		return true;
	}

	/*
	 * 下订单通知员工及用户下单成功
	 */
	public static function sendNotice($param) {
		sleep(1);
		self::SendTuanOrderSuccessNotice($param);//组团成功以后发送消息
		$sendId = self::satisfyCouponDistribute($param);
		if($sendId){
			$result['sendId']=$sendId;
			Output::instance()->object($result);
			return $result;
		}
		Output::instance()->resultCode(code_success);
	}
	//是否派发优惠券
	public static function satisfyCouponDistribute($param){
		$id=$param->id;
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$couponScheme = M("module_coupon_scheme");
		$order = M("module_product_order");
		$orderDetail = M("module_product_order_detail");
		Session::switchCustomer($cid);
		$nowTime = date("Y-m-d H:i:s");
		$schemeWhere['isDefault']=array("eq",1);
		$schemeWhere['cId']=array("eq",$cid);
		$schemeWhere['deleted']=array("eq",0);
		$schemeWhere['status']=array("eq",1);
		$schemeWhere["_string"]="(isEffective=1 and startTime < '$nowTime' and endTime> '$nowTime') or isEffective=0";
		$schemeInfo = $couponScheme->where($schemeWhere)->find();
		$ids = explode(",",$id);
		$orderWhere['id']=array("in",$ids);
		if($schemeInfo){
			$orderList = $order->where($orderWhere)->select();
			foreach($orderList as $value){
				if($schemeInfo['accOrderPrice']!=1&&$schemeInfo['accProductTags']!=1){
					continue;
				}
				if($schemeInfo['accOrderPrice']==1){
					if($value['price']>=$schemeInfo['minPrice']){
						//发送优惠券
						$reduction = true;
					}else{
						$reduction = false;
					}
				}else{
					$reduction = true;
				}
				if($schemeInfo['accProductTags']==1){
					$satisfy = false;
					$orderDetailWhere['a.oid']=array("eq",$value['id']);
					$tagList = $orderDetail->alias("a")
						->join("inner join wx_module_product_tag_list b on a.pid=b.pid")
						->where($orderDetailWhere)
						->field("b.tagId")
						->group("b.tagId")
						->select();
					$proTagList = explode(",",$schemeInfo['productTags']);
					foreach($tagList as $key=>$value){
						if(in_array($value['tagId'],$proTagList)){
							$satisfy = true;
							break;
						}
					}
				}else{
					$satisfy = true;
				}
				if($satisfy&&$reduction){
					//发送优惠券
					$sendId =self::sendCouponToUser($schemeInfo['id'],$id);
					return $sendId;
				}
			}
		}
		return;
	}
	//派发优惠券
	public static function sendCouponToUser($schemeId,$oid=null,$status=0,$token=NULL){
		$token = Module::callModule("personCenter",null,"verifyToken",$token);
		$cid = Session::$user["customerId"];
		$userName = Session::$user['userName'];
		$userId = Session::$user['userId'];
		Session::switchCustomer(0);
		$couponModel = M("module_coupon");
		$sendModel = M("module_coupon_send");
		$sendDetailModel = M("module_coupon_send_detail");
		$userCoupon = M("module_user_coupon");
		$schemeCoupon = M("module_coupon_scheme");
		Session::switchCustomer($cid);
		$schemeInfo = $schemeCoupon->where("id=$schemeId")->field("receiveType")->find();
		//每张优惠券派发张数
		if($status){
			$sendWhere['openid']=array("eq",$userName);
			$sendWhere['schemeId']=array("eq",$schemeId);
			$sendWhere['cId']=array("eq",$cid);
			$sendResult = $sendModel->where($sendWhere)->find();
			if($sendResult){
				$selfCondition['openid']=array("eq",$userName);
				$selfCondition['sendId']=array("eq",$sendResult['id']);
				$selfCondition['cId']=array("eq",$cid);
				$receiveResult = $userCoupon->alias("a")
					->join("inner join wx_module_coupon b on a.couponId=b.id")
					->field("b.*")
					->where($selfCondition)->select();
				if($receiveResult||$schemeInfo['receiveType']){
					$location = C("SERVER_HOST") . "call.html?customerId=$cid&scope=1&module=product&method=receiveCoupon&params=%7B%22sendId%22:".$sendResult['id']."%7D";
					redirect($location);
					return;
				}else{
					$param = new stdClass();
					$param->sendId=$sendResult['id'];
					Module::callModule("product", NULL,"couponIndex", $param);
					return;
				}
			}
			$sendData['fromModule']='url';
		}else{
			$sendData['fromModule']='order';
			$sendData['moduleId']=$oid;
		}

		$couponCount = 1;
		$couponWhere["schemeId"]=array("eq",$schemeId);
		$couponWhere["deleted"]=array("eq",0);
		$couponWhere["surplusNum"]=array("gt",0);
		$couponModel->startTrans();
		$couponList = $couponModel->where($couponWhere)->select();
		if($couponList&& ($userName || $userId)){//LP修改
			$couponInfo = $couponModel->where($couponWhere)->field("count(id) as copiesNum,sum(money*$couponCount) as copiesPrice")->find();
			$sendData['cId']=$cid;
			$sendData['openid']=$userName;
			$sendData['copiesPrice']=$couponInfo['copiesPrice'];
			$sendData['copiesNum']=$couponInfo['copiesNum'];
			$sendData['surplusPrice']=$couponInfo['copiesPrice'];
			$sendData['surplusNum']=$couponInfo['copiesNum'];
			$sendData['schemeId']=$schemeId;
			$sendData['createTime']=date("Y-m-d H:i:s");
			$sendData['userId']=$userId;	//LP修改
			$sendId=$sendModel->add($sendData);
			if($sendId){
				foreach($couponList as $key=>$value){
					$sendDetail[$key]['sendId']=$sendId;
					$sendDetail[$key]['couponId']=$value['id'];
					$sendDetail[$key]['copiesNum']=$couponCount;
					$sendDetail[$key]['surplusNum']=$couponCount;
					$sendDetail[$key]['createTime']=date("Y-m-d H:i:s");
					$sendDetail[$key]['updateTime']=date("Y-m-d H:i:s");
				}
				$addAllResult = $sendDetailModel->addAll($sendDetail);
				if($addAllResult){
					$sql = "update wx_module_coupon set surplusNum=surplusNum-1 where schemeId=$schemeId and deleted=0 and surplusNum>0";
					$result = $couponModel->query($sql);
					if($result!==false){
						$couponModel->commit();
						if($schemeInfo['receiveType']&&$status){
							$location = C("SERVER_HOST") . "call.html?customerId=$cid&scope=1&module=product&method=receiveCoupon&params=%7B%22sendId%22:".$sendId."%7D";
							redirect($location);
							return;
//							$param = new stdClass();
//							$param->sendId=$sendId;
//							Module::callModule("product", NULL,"receiveCoupon", $param);
//							return;
						}
						if($status){
							$param = new stdClass();
							$param->sendId=$sendId;
							Module::callModule("product", NULL,"couponIndex", $param);
							return;
						}
						return $sendId;
					}
				}
			}
		}
		$couponModel->rollback();
		if($status){
			Module::callModule("product", NULL,"couponEmpty", null);
			return;
		}
		return false;
	}
	//优惠券扫码事件
    public function scanCouponCode($param){
        $schemeId = $param->id;
        $userName = $param->message->fromUserName;
        $codeId = $param->codeId;
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $couponModel = M("module_coupon");
        $sendModel = M("module_coupon_send");
        $sendDetailModel = M("module_coupon_send_detail");
        $userCoupon = M("module_user_coupon");
        $couponScheme = M("module_coupon_scheme");
        $code = M("qrcode");
        Session::switchCustomer($cid);
		$UserModel = M('user');
		$userId = $UserModel->where(['userName' => $userName])->getField('id');
        $schemeInfo = $couponScheme->where("id=$schemeId")->find();
        if(!$schemeInfo['status']||$schemeInfo['deleted']){
            WeixinApi::sendServiceMsg($userName,"text","该二维码对应的优惠券已经被删除或者停用。");
            return;
        }
        $time = time();
        if($schemeInfo['isEffective']==1&&(strtotime($schemeInfo['startTime'])>$time||strtotime($schemeInfo['endTime'])<$time)){
            WeixinApi::sendServiceMsg($userName,"text","该二维码对应的优惠券不再领取时间范围内。");
            return;
        }
        $materialModel = M("material");
        $weixinInfo = M("user_weixin_info");
        $userInfo = $weixinInfo->where("openid='$userName'")->find();
        $materialId = $schemeInfo["newsId"];
        $couponCount = 1;
        $couponWhere["schemeId"]=array("eq",$schemeId);
        $couponWhere["deleted"]=array("eq",0);
        $couponWhere["surplusNum"]=array("gt",0);
        $couponModel->startTrans();
        $couponList = $couponModel->where($couponWhere)->select();
        if($couponList&&$userName){
            $couponInfo = $couponModel->where($couponWhere)->field("count(id) as copiesNum,sum(money*$couponCount) as copiesPrice")->find();
            $sendData['cId']=$cid;
            $sendData['openid']=$userName;
            $sendData['copiesPrice']=$couponInfo['copiesPrice'];
            $sendData['copiesNum']=$couponInfo['copiesNum'];
            $sendData['surplusPrice']=$couponInfo['copiesPrice'];
            $sendData['surplusNum']=$couponInfo['copiesNum'];
            $sendData['schemeId']=$schemeId;
            $sendData['createTime']=date("Y-m-d H:i:s");
            $sendData['fromModule']='qrcode';
            $sendData['moduleId']=$codeId;
            $sendId=$sendModel->add($sendData);
            if($sendId){
                foreach($couponList as $key=>$value){
                    $sendDetail[$key]['sendId']=$sendId;
                    $sendDetail[$key]['couponId']=$value['id'];
                    $sendDetail[$key]['copiesNum']=$couponCount;
                    $sendDetail[$key]['surplusNum']=$couponCount;
                    $sendDetail[$key]['createTime']=date("Y-m-d H:i:s");
                    $sendDetail[$key]['updateTime']=date("Y-m-d H:i:s");
                }
                $addAllResult = $sendDetailModel->addAll($sendDetail);
                if($addAllResult){
                    $result = $couponModel->where("schemeId=$schemeId and deleted=0 and surplusNum>0")->setDec("surplusNum");
                    if($result){
                        $couponList = $sendDetailModel->alias("a")
                            ->join("inner join wx_module_coupon b on a.couponId=b.id")
                            ->field("a.*,b.money")
                            ->where("a.sendId=$sendId and a.surplusNum>0")->select();
                        $totalPrice = 0;
                        if($couponList&&$userName) {
                            foreach ($couponList as $key => $value) {
                                $data['openid'] = $userName;
                                $data['cId'] = $cid;
                                $data['schemeId'] = $schemeId;
                                $data['couponId'] = $value['couponId'];
                                $data['sendDetailId'] = $value['id'];
                                $data['number'] = 1;
                                $data['createTime'] = date("Y-m-d H:i:s");
                                $data['sendId'] = $sendId;
                                $data['userId'] = $userId;
                                $userCouponId = $userCoupon->add($data);
                                $totalPrice+=$value['money'];
                                if ($userCouponId) {
                                    $sql = 'update wx_module_coupon_send_detail set surplusNum=surplusNum-1 where id=' . $value['id'];
                                    $sendDetailModel->query($sql);
                                    $sql = 'update wx_module_coupon_send set surplusNum=surplusNum-1,surplusPrice=surplusPrice-' . $value['money'] . ' where id=' . $value['sendId'];
                                    $sendDetailModel->query($sql);
                                }
                            }
                        }
                    }
                }
                $code->where("id=$codeId")
                    ->setField("method","scanedCode");
                $materialInfo = $materialModel->where("id=".$materialId)->find();
                $xml = (string)$materialInfo["xml"];
                $xml = str_replace("{{nickname}}",$userInfo['nickname'],$xml);
                $xml = str_replace("{{price}}",$totalPrice,$xml);
                $xml = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
                $item = $xml->Articles->item;
                $articles=array();
                foreach($item as $key=>$value){
                    $article=new stdClass();
                    $article->title = urlencode((string)$value->title);
                    $article->url = urlencode((string)$value->url);
                    $article->picurl = urlencode((string)$value->picUrl);
                    $article->description = urlencode((string)$value->description);
                    array_push($articles, $article);
                }
                $toUser = $userName;
                WeixinApi::sendServiceMsg($toUser, 'news','',$articles);
                $couponModel->commit();
                return;
            }
        }else{
            WeixinApi::sendServiceMsg($userName,"text","该二维码对应的优惠券已经被领光。");
            return;
        }
        $couponModel->rollback();
        return false;
    }
    public function scanedCode($param){
        $userName = $param->message->fromUserName;
        $schemeId = $param->id;
        $codeId = $param->codeId;
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $sendModel = M("module_coupon_send");
        Session::switchCustomer($cid);
        $where['a.moduleId']=array("eq",$codeId);
        $where['a.schemeId']=array("eq",$schemeId);
        $where['a.fromModule']=array("eq",'qrcode');
        $result = $sendModel->alias("a")
            ->join("wx_".$cid."_user_weixin_info b on a.openid=b.openid")
            ->where($where)
            ->field("b.nickname,a.createTime")
            ->find();
        WeixinApi::sendServiceMsg($userName,"text","该二维码对应的优惠券已经被领取过了，无法再次领取。领取人是".$result['nickname'].",领取时间是".$result["createTime"]);
    }
	private static function SendQuanOrderNotice($param){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$orderModel = M("module_product_order");
		$mimallUser = M("mimall_user");
		$miyouquan = M('miyouquan');
		Session::switchCustomer($cid);
		$TemplateModel = M("template_messages");
		$oid=explode(",",$param->id);
		//Log::write('jie---oid'.print_r($oid, true));
		foreach($oid as $key=>$id){
			//Log::write('jie---11');
			$toUserInfo = $orderModel->alias("a")
				->join("inner join wx_module_product_order_detail e on e.oid=a.id")
				->join("wx_".$cid."_user_weixin_info d on a.fromUserName=d.openid")
				->field("a.qId,a.serialNumber,a.price,a.type,a.fullName,a.phone,a.createTime,a.miUid as uid,a.refereeUid,
			a.parentRefereeUid as parRefereeUid,a.saleSource,a.points,d.nickname,sum(e.isMiUserCut) as isMiUserCut,
			sum(e.isRefereeCut) as isRefereeCut,sum(e.isParentRefereeCut) as isParentRefereeCut")
				->where("a.id=$id")
				->find();
			Log::write("合伙人订单提醒  ".$orderModel->getLastSql());
			$quanInfo = $miyouquan->where("id=".$toUserInfo['qId'])->find();
			$phone =substr($toUserInfo['phone'],0,3)."*****".substr($toUserInfo['phone'],-3);
			$fullName = substr($toUserInfo['fullName'],0,3)."**";
			$twhere['status']=array("eq","partnerorder");
			$templatemsg = $TemplateModel->where($twhere)->find();
			$templateId = $templatemsg['templateId'];
			$mimallWhere['qId']=array("eq",$toUserInfo['qId']);
			$mimallWhere['cId']=array("eq",$cid);
			$customer = WeixinApi::getCustomer();
			if($customer['mode']&&$customer['grantStatus']){
				$domainName = $customer["appid"];
				$http['RESOURCEURL']="http://".$domainName.".".C('NEWRESOURCEURL');
			}else{
				$http['RESOURCEURL'] = C("SERVER_NAME").'/';
			}
			//$http = WeixinApi::getDomainName();
			$urls = $http['RESOURCEURL'] . "spa/index.html#/quan/myOrder/normalDetail/".$id.'?customerId='.$cid.'&params=%7B%22qId%22%3A'.$toUserInfo['qId'].'%7D';
			$marketingUrl = $http['RESOURCEURL'] . "spa/index.html#/quan/myOrder/marketingDetail/".$id.'?customerId='.$cid.'&params=%7B%22qId%22%3A'.$toUserInfo['qId'].'%7D';
			/*$urls = C("SERVER_HOST") . "call.html?customerId=" . $cid .
				"&module=quan&method=order&params=%7B%22qId%22:".$toUserInfo['qId']."%7D";*/
			$first = '恭喜！您的好友'.$toUserInfo['nickname'].'新下了一个订单。';
			if($toUserInfo['type'] == ORDER_TYPE_FORM){
				$urls = $marketingUrl;
				$first = '您的好友'.$toUserInfo['nickname'].'提交新的信息了。';
			}
			if ($toUserInfo['type'] == ORDER_TYPE_POINT) {
				$outNum = $toUserInfo['points'] . '积分';
			} else {
				$outNum = $toUserInfo['price'] . '元';
			}
			if($toUserInfo['uid']){
				$mimallWhere['uId']=array("eq",$toUserInfo['uid']);
				$refereeInfo = $mimallUser->where($mimallWhere)->field("openid")->find();
				Log::write("合伙人订单提醒（自己）  ".$id."---".$mimallUser->getLastSql());
				$data['first'] = array('value'=> $first,'color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $toUserInfo["serialNumber"],'color'=>'#173177');
				$data['keyword2'] = array('value'=> $outNum,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $fullName,'color'=>'#173177');
				$data['keyword4'] = array('value'=> $phone,'color'=>'#173177');
				$data['keyword5'] = array('value'=> $toUserInfo["createTime"],'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看订单详情',"color"=>'#008000');
				$toUser = $refereeInfo['openid'];
				$url = urlencode($urls);
				$topcolor = "#FF0000";
				WeixinApi::sendTpl($toUser, $templateId, $url,$topcolor,$data,true,$cid);
			}
			if($toUserInfo['refereeUid']&&$quanInfo['refereeAward']>0){
				$mimallWhere['uId']=array("eq",$toUserInfo['refereeUid']);
				$parRefereeInfo = $mimallUser->where($mimallWhere)->field("openid")->find();
				Log::write("合伙人订单提醒（推荐人）  ".$id."---".$mimallUser->getLastSql());
				$data['first'] = array('value'=> $first,'color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $toUserInfo["serialNumber"],'color'=>'#173177');
				$data['keyword2'] = array('value'=> $outNum,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $fullName,'color'=>'#173177');
				$data['keyword4'] = array('value'=> $phone,'color'=>'#173177');
				$data['keyword5'] = array('value'=> $toUserInfo["createTime"],'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看订单详情',"color"=>'#008000');
				$toUser = $parRefereeInfo['openid'];
				$url = urlencode($urls);
				$topcolor = "#FF0000";
				WeixinApi::sendTpl($toUser, $templateId, $url,$topcolor,$data,true,$cid);

			}
			if($toUserInfo['parRefereeUid']&&$quanInfo['parentRefereeAward']>0){
				$mimallWhere['uId']=array("eq",$toUserInfo['parRefereeUid']);
				$teamLeaderInfo = $mimallUser->where($mimallWhere)->field("openid")->find();
				Log::write("合伙人订单提醒（二级推荐人）  ".$id."---".$mimallUser->getLastSql());
				$data['first'] = array('value'=> $first,'color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $toUserInfo["serialNumber"],'color'=>'#173177');
				$data['keyword2'] = array('value'=> $outNum,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $fullName,'color'=>'#173177');
				$data['keyword4'] = array('value'=> $phone,'color'=>'#173177');
				$data['keyword5'] = array('value'=> $toUserInfo["createTime"],'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看订单详情',"color"=>'#008000');
				$toUser = $teamLeaderInfo['openid'];
				$url = urlencode($urls);
				$topcolor = "#FF0000";
				WeixinApi::sendTpl($toUser, $templateId, $url,$topcolor,$data,true,$cid);
			}
			if($toUserInfo['saleSource']){
				$mimallWhere['uId']=array("eq",$toUserInfo['saleSource']);
				$teamLeaderInfo = $mimallUser->where($mimallWhere)->field("openid")->find();
				$urls = $http['RESOURCEURL'] . "spa/index.html#/quan/orderManage/normalDetail/".$id.'?customerId='.$cid.'&params=%7B%22qId%22%3A'.$toUserInfo['qId'].'%7D';
				$first =  '恭喜，您的客户'.$toUserInfo['nickname'].'新下了一个订单。';
				if($toUserInfo['type'] == ORDER_TYPE_FORM){
					$urls = $http['RESOURCEURL'] . "spa/index.html#/quan/orderManage/marketingDetail/".$id.'?customerId='.$cid.'&params=%7B%22qId%22%3A'.$toUserInfo['qId'].'%7D';
					$first =  '您的客户'.$toUserInfo['nickname'].'提交新的信息了。';
				}
				Log::write("销售源  ".$id."---".$mimallUser->getLastSql());
				$data['first'] = array('value'=> $first,'color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $toUserInfo["serialNumber"],'color'=>'#173177');
				$data['keyword2'] = array('value'=> $outNum,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $fullName,'color'=>'#173177');
				$data['keyword4'] = array('value'=> $phone,'color'=>'#173177');
				$data['keyword5'] = array('value'=> $toUserInfo["createTime"],'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看订单详情',"color"=>'#008000');
				$toUser = $teamLeaderInfo['openid'];
				$url = urlencode($urls);
				$topcolor = "#FF0000";
				WeixinApi::sendTpl($toUser, $templateId, $url,$topcolor,$data,true,$cid);
			}
		}
	}

	private function SendVirtualCode($param) {
		$cid = Session::$user["customerId"];
		$VerifyCode = M("module_verify_code");
		Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		$OrderDetailModel = M("module_product_order_detail");
		Session::switchCustomer($cid);
		$id=$param->id;
		$userName=$param->userName;
		$where['id'] = $id;
		$order = $OrderModel->where($where)->find();
		if(!$order || $order["isVirtual"]!="1") {
			return;
		}

		$info=$OrderModel->alias("a")
		->join("inner join wx_module_product_order_detail b on a.id=b.oid")
		->join("inner join wx_module_product c on c.id=b.pid")
		->join("inner join wx_".$cid."_module_verify_code d on d.oid=a.id")
		->field("a.id,c.name,c.virtualInfo,c.virtualEndTime,group_concat(d.code) as code")
		->where("a.id=$id")
		->find();
		$TemplateModel = M("template_messages");
		$twhere['status'] = array("eq","virtual");
		$templatemsg = $TemplateModel->where($twhere)->find();
		$templateId = $templatemsg['templateId'];
		$data['first'] = array('value'=> '优惠券在这里，戳我！戳我！戳我！','color'=>"#743A3A");
		$data['keyword1'] = array('value'=> $info["name"],'color'=>'#173177');
		$data['keyword2'] = array('value'=> $info["code"],'color'=>'#173177');
		$data['keyword3'] = array('value'=> '至'.date ("Y年m月d日",strtotime($info["virtualEndTime"]))."\n",'color'=>'#173177');
		$data['remark'] = array('value'=> '点击查看优惠券验证码',"color"=>'#008000');
		$toUser = $userName;
		$template_id = $templateId;
		$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
			"&module=product&method=virtualSuccess&params=%7B%22id%22:$id%7D";
		$url = urlencode($url);
		$topcolor = "#FF0000";
		WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
//		if($info) {
//			$text=$info["name"]."\n";
//			$text.="验证码：".$info["code"]."\n";
//			$text.="有效期至：".date ("Y年m月d日",strtotime($info["virtualEndTime"]))."\n";
//			$text.="使用规则：".$info["virtualInfo"];
//		}
//		WeixinApi::sendText($userName,$text);
	}
	private function createCode($fromUserName, $order, $count = 1,$virtualEndTime=null,$disabled=0) {
		$VerifyCode = M("module_verify_code");
		$data = array();
		$oid=$order["id"];
		for ($i = 0; $i < $count; $i++) {
			// 生成验证码如果数据库中已经存在则重新生成
			do {
				// 生成6位随机验证码
				$code = rand(100000000000, 999999999999);
			} while ($VerifyCode->where("code='$code'")->find());
			// 将验证码存储到数据库
			$data[$i]['fromUserName'] = $fromUserName;
			$data[$i]['oid'] = $oid;
			$data[$i]['code'] = (String)$code;
			$data[$i]['materialId'] = 0;
			$data[$i]['disabled'] = $disabled;
			$data[$i]['reward'] = $order["proname"];
			$data[$i]['module'] ="product";
			$data[$i]['validateEndTime']=$virtualEndTime;
			$data[$i]['createTime'] = date('Y-m-d H:i:s');
			if($order["isVirtual"] && $order["isTeam"]!="1") { //虚拟非团购商品发货更新订单
				if($order['deliveryType']=='delivery'){
					$VerifyCode->query("update wx_module_product_order set status='delivering' where id=$oid");
				}else if($order['deliveryType']=='pickup'){
					$VerifyCode->query("update wx_module_product_order set status='deliveringtostore' where id=$oid");
				}
			}
		}
		$result = $VerifyCode->addAll($data);
		return $data;
	}
	private function num_format($num,$str){
		if (!is_numeric($num)) {
			return false;
		}
		$num = explode('.', $num); // 把整数和小数分开
		$rl = $num[1]; // 小数部分的值
		$j = strlen($num[0]) % 4; // 整数有多少位
		$sl = substr($num[0], 0, $j); // 前面不满三位的数取出来
		$sr = substr($num[0], $j); // 后面的满三位的数取出来
		$i = 0;
		$rvalue='';
		while ($i <= strlen($sr)) {
			$rvalue = $rvalue . $str . substr($sr, $i, 4); // 三位三位取出再合并，按逗号隔开
			$i = $i + 4;
		}
		$rvalue = $sl . $rvalue;
		$rvalue = substr($rvalue, 0, strlen($rvalue) - 1); // 去掉最后一个逗号
		$rvalue = explode(',', $rvalue); // 分解成数组
		if ($rvalue[0] == 0) {
			array_shift($rvalue); // 如果第一个元素为0，删除第一个元素
		}
		$rv = $rvalue[0]; // 前面不满三位的数
		for ($i = 1; $i < count($rvalue); $i++) {
			$rv = $rv . ',' . $rvalue[$i];
		}
		if (!empty($rl)) {
			$rvalue = $rv . '.' . $rl; // 小数不为空，整数和小数合并
		} else {
			$rvalue = $rv; // 小数为空，只有整数
		}
		return trim($rvalue);
	}
	/**
	 * [createVirtualCode 虚拟商品创建验证码]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function createVirtualCode($param) {
		$cid = Session::$user["customerId"];
		$VerifyCode = M("module_verify_code");
		Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		$OrderTeamModel=M("module_team_order");
		$OrderTeamDetailModel=M("module_team_order_detail");
		$OrderDetailModel = M("module_product_order_detail");
		Session::switchCustomer($cid);
		$id=$param->id;
		$userName=$param->userName;
		$where['id'] = $id;
		$order = $OrderModel->where($where)->find();
		if(!$order || $order["isVirtual"]=="0" ) {
			return;
		}
		$detail=$OrderDetailModel->alias("a")
		->join("inner join wx_module_product b on a.pid=b.id")
		->field("a.id,a.oid,a.pid,a.count,b.virtualEndTime,b.name")
		->where("a.oid=$id")->select();

		$condition['fromUserName'] = array('eq',$userName);
		$condition['oid'] = array('eq',$id);
		$isCreate= $VerifyCode->where($condition)->select();
		$disabled=0;
		if($detail && count($isCreate) < 1) {
			if(count($detail) > 0) {
				$value=$detail[0];
				$count=$value["count"];
				$order["proname"]=$value["name"];
				$virtualEndTime=$value["virtualEndTime"];
				if($order["isTeam"]) { //如果是团购订单
					$teamId=$order["teamId"];
					$teamOrder=$OrderTeamModel->where("id=$teamId")->find();
					if($teamOrder) {
						if($teamOrder["status"] > 0){ //团购成功,更新所有订单验证码为可用
							$disabled=1;
						}
					}
				} else { //非团购商品
					$disabled=1;
				}
				$data=self::createCode($userName,$order,$count,$virtualEndTime,$disabled);
			}
		}
	}
	//夺宝分配号码
	public function SendIndianaCode($param){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$periodModel = M("module_mill_period");
		$OrderModel = M("module_product_order");
		$numberModel = M("module_mill_number");
		$parModel = M("module_mill_par");
		Session::switchCustomer($cid);
		$id=$param->id;
		$userName=$param->userName;
		$where['a.id'] = $id;
		$order = $OrderModel->alias("a")
			->join("inner join wx_module_product_order_detail b on a.id=b.oid")
			->join("inner join wx_module_product c on b.pid = c.id")
			->where($where)
			->field("a.*,b.pid,b.count,c.totalCopies")
			->find();
		if($order["orderType"]==3){
			$parInfo = $parModel->where("id=".$order["playOrderId"])->field("id,count,perId")->find();
			$surplus = self::indianaRandCode($parInfo["count"],$parInfo["perId"],$order["playOrderId"],$userName,$order["id"],$order["pid"],$order["totalCopies"]);
		}
	}
	public function indianaRandCode($count,$perId,$parId,$username,$oid,$pid,$totalCopies){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$numberModel = M("module_mill_number");
		$periodModel = M("module_mill_period");
		$productModuel = M("module_product");
		$parModel = M("module_mill_par");
		Session::switchCustomer($cid);
		$periodInfo = $periodModel->where("id=".$perId)->field("surplus,beenSold")->find();
		$surplus = $periodInfo["surplus"];
		$beenSold = $periodInfo["beenSold"];
		for($i=0;$i<$count;$i++){
			$surplus--;
			$beenSold++;
			$numberList = $numberModel->where("parId is null and perId=".$perId)->select();
			$random = rand(0,count($numberList)-1);
			$numberInfo = $numberList[$random];
			$numberData["openId"]=$username;
			$numberData["parId"] = $parId;
			$numberModel->startTrans();
			$nResult = $numberModel->where("id=".$numberInfo["id"])->save($numberData);
			$periodData["surplus"] = $surplus;
			$periodData["beenSold"]=$beenSold;
			$periodResult = $periodModel->where("id=".$perId)->save($periodData);
			if($nResult==false||$periodResult==false){
				$numberModel->rollback();
			}else{
				$numberModel->commit();
			}
		}
		if($surplus<=0){
			//存最后50人的时间和并且变成待开奖
			$timeList = $parModel->alias("a")
				->join("wx_module_product_order b on a.oid=b.id")
				->where("a.perId=".$perId." and b.status = 'partake'")
				->field("a.updateTime")->order("a.id desc")->limit(0,50)->select();
			$timeTogether = 0;
			foreach($timeList as $key=>$value){
				$h = date("H",strtotime($value["updateTime"]));
				$m = date("i",strtotime($value["updateTime"]));
				$s = date("s",strtotime($value["updateTime"]));
				$timeTogether += floor($h.$m.$s);
			}
			$periodModel->startTrans();
			$data["periodState"]=2;
			$data["updataTime"]=date("y-m-d H:i:s");
			$data["timeTogether"] = $timeTogether;
			$periodResult = $periodModel->where("id=".$perId)->save($data);
			if($periodResult==false){
				$periodModel->rollback();
			}else{
				$periodModel->commit();
			}
			$result = self::indianaProductInventory($pid);
			if($result['inventory']=="0"||($result['inventory']=="1"&&$result['inventoryCount']>0)) {
				self::startNewPeriod($pid,$totalCopies);
			}
		}
		return $surplus;
	}
	public static function indianaProductInventory($pid){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$productModuel = M("module_product");
		Session::switchCustomer($cid);
		$productInfo=$productModuel->where("id=".$pid)->find();
		$inventoryCount = $productInfo["inventoryCount"];
		if($productInfo["inventory"]==1&&$productInfo["inventoryCount"]>0){
			$inventoryCount = $inventoryCount-1;
			$productModuel->where("id=".$pid)->setField('inventoryCount',$inventoryCount);
		}
		$result["inventory"] = $productInfo["inventory"];
		$result["inventoryCount"] = $inventoryCount;
		return $result;
	}
	/**
	 * [SendTuanOrderSuccessNotice description]
	 * @param [type] $param [description]
	 */
	public function SendTuanOrderSuccessNotice($param){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		$OrderTeamModel = M("module_team_order");
		Session::switchCustomer($cid);
		$id=$param->id;
		$userName=$param->userName;
		$where['id'] = $id;
		$order = $OrderModel->where($where)->find();
		if($order["isTeam"]) {
			$teamId=$order["teamId"];
			$orderTeam=$OrderTeamModel->where("id=$teamId")->find();
			$preTeamStatus=$orderTeam["status"];
			if($orderTeam && $orderTeam["status"]=="1") {
				$status="delivering";
				if($order["isVirtual"]==1) {
					$status="delivered";
				}
				$OrderTeamModel->where("id=$teamId")->setField("status",2);
				$orderList=$OrderModel->where("teamId=$teamId and status='$status'")->select();
				foreach ($orderList as $key => $value) {
					$id=$value["id"];
					$fromUserName=$value["fromUserName"];
					$p=new stdClass();
					$p->id=$id;
					$p->userName=$fromUserName;
					$p->type="tuanComplete";
					self::SendorderNotice($p);
					//虚拟商品发送验证码
					if($value["isVirtual"]=="1") { //团购成功以后
						$param->id=$id;
						$param->userName=$fromUserName;
						self::SendVirtualCode($param);
					}
				}
			}
			if($orderTeam["status"] > 1 && $preTeamStatus!="1") { //团购成功以后
				self::SendVirtualCode($param);
			}
		} else { //非团购虚拟商品
			if($order["isVirtual"]=="1") {
				self::SendVirtualCode($param);
			}
		}
	}

	/**
	 * [SendorderNotice 模板消息，暂时未考虑拆单，可适时增加]
	 * @param [type] $id       [订单id]
	 * @param [type] $userName [openid]
	 */
	public static function SendorderNotice($param){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		$OrderTeamModel = M("module_team_order_detail");
		$parModel = M("module_mill_par");
		$storeModel = M("store");
		$orderDetail = M("module_product_order_detail");
		Session::switchCustomer($cid);
		$TemplateModel = M("template_messages");
		$userModel = M("user");
		$ids=explode(",",$param->id);
		$userName=$param->userName;
		foreach($ids as $key=>$value){
			$where['id'] = $value;
			$order = $OrderModel->where($where)->find();
			$status = $order["status"];
			$type=$param->type;
			if($status==order_status_deliveringtostore){
				//$twhere['status'] = order_status_delivering;
				$twhere['status'] = new_order_status_delivering;
			}else{
				$twhere['status'] = $status;
				/*优先使用电子商务 不存在,再使用IT软件与服务, jie 2017-11-23*/
				switch($status){
					case order_status_delivering:
						$twhere['status'] = new_order_status_delivering;
						break;
					/*case ORDER_STATUS_REFUNDEDPART:
						$twhere['status'] = order_status_refund;	//部分退款暂时没有模板消息
						break;*/
					default:
						break;
				}
			}
			$templatemsg = $TemplateModel->where($twhere)->find();
			if($templatemsg == null){
				switch($twhere['status']){
					case new_order_status_delivering:
						$twhere['status'] = order_status_delivering;
						break;
					default:
						break;
				}
				$templatemsg = $TemplateModel->where($twhere)->find();
			}
			if(empty($templatemsg['templateId'])){
				Log::write('templateId error:'.$TemplateModel->getLastSql());
			}

			$templateId = $templatemsg['templateId'];
			//订单号
			$descSn =  $order["serialNumber"];
			//下单时间
			$descTime = $order["createTime"];
			//价格
			$descPrice =  $order["price"] . '元';
			//积分
			$descPoint = $order['points'] . '积分';
			//快递公司
			$expressName = $order["expressName"];
			//快递单号
			$expressNo = $order["expressNo"];
			if($order["module"]!="" && ($order['orderType'] != ORDER_ORDERTYPE_NINE)) { //临时充值订单不发消息
				return;
			}
			if($status==order_status_deliveredtostore){
				$storeWhere['id']=$order['storeResourceId'];
				$storeInfo = $storeModel->where($storeWhere)->field("name,address,phone")->find();
				if($order['payType']=="wxpay"){
					$str = "微信支付";
				}else if($order['payType']=='tenpay'){
					$str = "银行卡支付";
				}
				$data['first'] = array('value'=> '亲爱的，你的商品已经到达自提点啦！','color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $descSn,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $storeInfo['name']."(".$storeInfo['address'].",".$storeInfo["phone"].")",'color'=>'#173177');
				$data['keyword3'] = array('value'=> $str,'color'=>'#173177');
				$data['keyword4'] = array('value'=> $descPrice,'color'=>'#173177');
				$data['keyword5'] = array('value'=> $order['createTime'],'color'=>'#173177');
				$data['remark'] = array('value'=> '赶紧前去领回家吧！点击查看订单详情。',"color"=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '赶紧前去领回家吧！点击查看订单详情。';
                $data_JPush['extra']['title'] = '您的商品已经到达自提点啦！';
                //20180723mh增加短信发送
                $smsInfo['status'] = 'deliveredtostore';
                $smsInfo['message'] = "您好，请凭取件码：".$order['pickupCode']."，至".$storeInfo['address']."取件";
                $templateParam['code'] = $order['pickupCode'];
                $templateParam['address'] = $storeInfo['address'];
                $templateParam = json_encode($templateParam);
                $smsInfo['templateParam'] = $templateParam;
			}
			if($status=='supported'){
				$name = $orderDetail->where("oid=$value")->getField("name");
				$data['first'] = array('value'=> '亲，您已经成功支付！','color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $descSn,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $name,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $descPrice,'color'=>'#173177');
				$data['keyword4'] = array('value'=> $descTime,'color'=>'#173177');
				$data['remark'] = array('value'=> '感谢您对本项目的支持！',"color"=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '感谢您对本项目的支持！';
                $data_JPush['extra']['title'] = '亲，您已经成功支付！';
			}
			if($status==order_status_deliveringtostore){
				self::sendVendorNotice($order["vId"],$order['serialNumber'],$order['updateTime'],$order['price']);
				$storeWhere['id']=$order['storeResourceId'];
				$storeInfo = $storeModel->where($storeWhere)->field("name,address,phone")->find();
				$str = $descPrice."\n配送方式：到店自提"."\n门店名称：".$storeInfo['name']."\n门店电话：".$storeInfo['phone']."\n门店地址：".$storeInfo['address'];
				$data['first'] = array('value'=> '亲，您的订单已提交成功!','color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $descSn,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $descTime,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $str,'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看订单详情',"color"=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '点击查看订单详情';
                $data_JPush['extra']['title'] = '您的订单已提交成功!';
                //20180723mh增加短信发送
                $smsInfo['status'] = 'buy';
                $smsInfo['message'] = '您的订单已支付成功。我们会尽快发货，记得关注我们的商城喔~感谢您的支持！';
                $smsInfo['templateParam'] = '';
			}
			if ($status == 'delivering') {
				if($order['orderType'] == ORDER_ORDERTYPE_NINE){
					/*您填写的信息已提交成功，我们将尽快确认*/
					$first = '您填写的信息已提交成功，我们将尽快确认。';
					//20180723mh增加短信发送
					$smsInfo['status'] = 'form';
					$smsInfo['message'] = '您填写的表单已提交成功';
					$smsInfo['templateParam'] = '';
				}else{
					$first = '您的订单已提交成功。';
                    //20180723mh增加短信发送
                    $smsInfo['status'] = 'buy';
                    $smsInfo['message'] = '您的订单已支付成功。我们会尽快发货，记得关注我们的商城喔~感谢您的支持！';
                    $smsInfo['templateParam'] = '';
				}
				if ($order['type'] == ORDER_TYPE_POINT) {
					$outNum = $descPoint;
				} else {
					$outNum = $descPrice;
				}
				self::sendVendorNotice($order["vId"],$order['serialNumber'],$order['updateTime'],$order['price']);
				$data['first'] = array('value'=> $first,'color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $descSn,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $descTime,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $outNum,'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看订单详情',"color"=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '点击查看订单详情';
                $data_JPush['extra']['title'] = $first;
            }
			if($status == 'partake'){
				$data['first'] = array('value'=> 'OK，您已经购买成功！请等待系统为您揭晓，开奖后会有消息提示！祝您好运！','color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $descSn,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $descTime,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $descPrice,'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看夺宝详情',"color"=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '点击查看夺宝详情';
                $data_JPush['extra']['title'] = 'OK，您已经购买成功！请等待系统为您揭晓，开奖后会有消息提示！祝您好运！';
            }
			if ($status == 'delivered') {
			    $red = self::commentRequire($value);
			    if($red){
			        $remark = '收货后请及时确认收货，晒单还有红包可以领哦。';
                }else{
                    $remark = '订单详情';
                }
				$data['first'] = array('value'=> '您的订单已经发货，请注意查收。','color'=>'#743A3A');
				$data['keyword1'] = array('value'=> $descSn,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $expressName,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $expressNo,'color'=>'#173177');
				$data['remark'] = array('value'=> $remark,'color'=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = $remark;
                $data_JPush['extra']['title'] = '您的订单已经发货，请注意查收。';
                //20180723mh增加短信发送
                $smsInfo['status'] = 'delivered';
                $smsInfo['message'] = "您的订单已发货，请注意查收。";
                $smsInfo['templateParam'] = '';
			}
			if ($status == 'paypart') {
				$data['first'] = array('value'=> '哈，还差一步即可成功购买：邀请好友参加活动，并且达到目标人数。','color'=>'#743A3A');
				$data['keyword1'] = array('value'=> $descSn,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $descTime,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $descPrice,'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看邀请进度','color'=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '点击查看邀请进度';
                $data_JPush['extra']['title'] = '哈，还差一步即可成功购买：邀请好友参加活动，并且达到目标人数。';
            }
			if($status=='teaming') {
				$data['first'] = array('value'=> '您的订单已提交成功，组团成功后即可发货。','color'=>'#743A3A');
				$data['keyword1'] = array('value'=> $descSn,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $descTime,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $descPrice,'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看组团进度','color'=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '点击查看组团进度';
                $data_JPush['extra']['title'] = '您的订单已提交成功，组团成功后即可发货。';
            }
			if(($status=="refund" || $status=="refundedpart")&&$order["isTeam"]==1) {
				$teamInfo = $OrderTeamModel->alias("a")
					->join("inner join wx_module_team_order b on a.teamId=b.id")
					->where("a.oid=$value")
					->find();
				if($teamInfo["role"]==1&&$teamInfo["isBack"]==1){
					$data["first"]=array('value' =>'你发起的组团购返现成功。','color'=>'#743A3A');
					$data['reason']=array('value'=>"你发起的组团购已经完成订单，团长享受现金返还。",'color'=>'#173177');
					$data['refund']=array('value'=>$order["price"]."元",'color'=>'#173177');
					$data['remark'] = array('value'=> '点击查看订单详情','color'=>'#008000');
					//mh添加极光推送信息20180428
                    $data_JPush['alert'] = '点击查看订单详情';
                    $data_JPush['extra']['title'] = '你发起的组团购返现成功。';
				}else{
					$data["first"]=array('value' =>'亲，您已经退款成功！请注意查收！','color'=>'#743A3A');
					$data['reason']=array('value'=>'订单'.$descSn.'交易未成功','color'=>'#173177');
					$data['refund']=array('value'=>$descPrice,'color'=>'#173177');
					$data['remark'] = array('value'=> '点击查看订单详情','color'=>'#008000');
					//mh添加极光推送信息20180428
                    $data_JPush['alert'] = '点击查看订单详情';
                    $data_JPush['extra']['title'] = '亲，您已经退款成功！请注意查收！';
				}
			}else if(($status=="refund" || $status=="refundedpart")&&$order["orderType"]==3) {
				$data["first"]=array('value' =>'意外！您收到了一笔夺宝的退款','color'=>'#743A3A');
				$data['reason']=array('value'=>"夺宝大富翁退款",'color'=>'#173177');
				$data['refund']=array('value'=>$order["price"]."元",'color'=>'#173177');
				$data['remark'] = array('value'=> '越努力，越幸运，再来一发，一定中！','color'=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '越努力，越幸运，再来一发，一定中！';
                $data_JPush['extra']['title'] = '意外！您收到了一笔夺宝的退款';
            }else if($status=="refund" || $status=="refundedpart") {
				$data["first"]=array('value' =>'已成功为您办理退款，请注意查收。','color'=>'#743A3A');
				$data['reason']=array('value'=>'订单'.$descSn.'交易未成功','color'=>'#173177');
				$data['refund']=array('value'=>$descPrice,'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看订单详情','color'=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '点击查看订单详情';
                $data_JPush['extra']['title'] = '已成功为您办理退款，请注意查收。';
            }
			if($type=="tuanComplete" && $status=="delivering" && $order["isVirtual"]!=1) { //组团实物
				$data['first'] = array('value'=> '恭喜您！订单已经组团成功。','color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $descSn,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $descTime,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $descPrice,'color'=>'#173177');
				$data['remark'] = array('value'=> '点击查看订单详情',"color"=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '点击查看订单详情';
                $data_JPush['extra']['title'] = '恭喜您！订单已经组团成功。';
            }
			if($type=="tuanComplete" && $status=="delivered" && $order["isVirtual"]==1) { //组团虚拟商品
                $red = self::commentRequire($value);
                if($red){
                    $remark = '惊喜预告：收货后，记得晒单，因为有红包等着你！';
                }else{
                    $remark = '点击查看详情';
                }
				$data['first'] = array('value'=> '亲，优惠券已经发出，请妥善保管哦！','color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $descSn,'color'=>'#173177');
				$data['keyword2'] = array('value'=> $descTime,'color'=>'#173177');
				$data['keyword3'] = array('value'=> $descPrice,'color'=>'#173177');
				$data['remark'] = array('value'=> $remark,"color"=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = $remark;
                $data_JPush['extra']['title'] = '亲，优惠券已经发出，请妥善保管哦！';
            }
			if( $status=="ordersign") { //报名提交
				$orderInfo = $orderDetail->alias("a")
					->join("inner join wx_module_product b on a.pid=b.id")
					->where("a.oid=$value")
					->field("a.name,b.activityinfo")
					->find();
				$activityinfo = json_decode($orderInfo['activityinfo'],true);
				$data['first'] = array('value'=> '亲，您已经报名成功啦！请耐心等待审核哦。','color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $orderInfo['name'],'color'=>'#173177');
				$data['keyword2'] = array('value'=> $activityinfo['activityTime'],'color'=>'#173177');
				$data['keyword3'] = array('value'=> $activityinfo['activityPlace'],'color'=>'#173177');
				$data['remark'] = array('value'=> '查看报名详情',"color"=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '查看报名详情';
                $data_JPush['extra']['title'] = '亲，您已经报名成功啦！请耐心等待审核哦。';
            }
			if( $status=="confirmsign") { //报名已确认
				$orderInfo = $orderDetail->alias("a")
					->join("inner join wx_module_product b on a.pid=b.id")
					->where("a.oid=$value")
					->field("a.name,b.activityinfo")
					->find();
				$activityinfo = json_decode($orderInfo['activityinfo'],true);
				$data['first'] = array('value'=> '亲，您的报名已经确认！相遇原是注定，活动因你精彩。','color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $orderInfo['name'],'color'=>'#173177');
				$data['keyword2'] = array('value'=> $activityinfo['activityTime'],'color'=>'#173177');
				$data['keyword3'] = array('value'=> $activityinfo['activityPlace'],'color'=>'#173177');
				$data['remark'] = array('value'=> '查看报名详情',"color"=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '查看报名详情';
                $data_JPush['extra']['title'] = '亲，您的报名已经确认！相遇原是注定，活动因你精彩。';
            }
			if( $status=="canclesign") { //报名已取消
				$orderInfo = $orderDetail->alias("a")
					->join("inner join wx_module_product b on a.pid=b.id")
					->where("a.oid=$value")
					->field("a.name,b.activityinfo")
					->find();
				$activityinfo = json_decode($orderInfo['activityinfo'],true);
				$data['first'] = array('value'=> '亲，报名已经取消了。迫切期望下次与你相遇。','color'=>"#743A3A");
				$data['keyword1'] = array('value'=> $orderInfo['name'],'color'=>'#173177');
				$data['keyword2'] = array('value'=> $activityinfo['activityTime'],'color'=>'#173177');
				$data['keyword3'] = array('value'=> $activityinfo['activityPlace'],'color'=>'#173177');
				$data['remark'] = array('value'=> '查看报名详情',"color"=>'#008000');
				//mh添加极光推送信息20180428
                $data_JPush['alert'] = '查看报名详情';
                $data_JPush['extra']['title'] = '亲，报名已经取消了。迫切期望下次与你相遇。';
            }
			$toUser = $userName;
			$template_id = $templateId;
			$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
				"&module=product&method=getOrderDetail&params=%7B%22tplid%22:1,%22id%22:$value%7D";

			if($status=="paypart") {
				$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
					"&module=freebuy&method=getView&params=%7B%22oid%22%3A%22$value%22%7D";
			}
			if($status=="teaming") {
				$teamId=$order["teamId"];
				$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
					"&module=tuan&method=getView&params=%7B%22teamId%22%3A%22$teamId%22%7D";
			}
			if($order['orderType'] == ORDER_ORDERTYPE_NINE){
				$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
					"&module=product&method=getOrderDetail&params=%7B%22id%22:".$value."%7D";
			}
			if($status == "partake"||$order["orderType"]==3){
				$parId=$order["playOrderId"];
				$parInfo = $parModel
					->where("id=".$parId)
					->field("pid,perId")->find();
				$pid = $parInfo["pid"];
				$perId = $parInfo["perId"];
				$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
					"&module=product&method=getProduct&params=%7B%22id%22%3A%22$pid%22%2C%22periodId%22%3A%22$perId%22%7D";
			}
			/*$http = WeixinApi::getDomainName();
			if($order['orderType'] == ORDER_ORDERTYPE_NINE){
				$url = $http['RESOURCEURL'] . "spa/index.html#/quan/myOrder/marketingDetail/".$order['id'];
			}*/

			$url = urlencode($url);
			$topcolor = "#FF0000";
			if(!$toUser){
				return;
			}
			//data得转json
			if($order["isVirtual"]=="1") {
				if($status!="delivered" || ($status=="delivered"  && $type=="tuanComplete")) {
					//添加信息推送时条件判断mh20180428
					if ($toUser){
						WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
					}
                    $userInfo = $userModel->field("JPUSHRegistrationID,phone")->where("id=".$order['uId'])->find();
                    //20180723mh增加短信发送
                    if ($userInfo['phone'] && $smsInfo) {
                        $params = new stdClass();
                        $params->phone = $userInfo['phone'];
                        $params->module = 'nmpOrder' ;
                        $params->status = $smsInfo['status'];
                        $params->message = $smsInfo['message'];
                        $params->templateParam = $smsInfo['templateParam'];
                        Module::callModule('phone', NULL, 'sendSms', $params);
                    }
					if ($userInfo['JPUSHRegistrationID']){
                        $data_JPush['extra']['extras']['load_url'] = urldecode($url);
						R("JPush/sendJPushMessage",array('android',[$userInfo['JPUSHRegistrationID']],'registrationId',$data_JPush['alert'],$data_JPush['extra']));
					}
				}
			} else {
				//WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
				//添加信息推送时条件判断mh20180428
				if ($toUser){
					WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
				}
                $userInfo = $userModel->field("JPUSHRegistrationID,phone")->where("id=".$order['uId'])->find();
				log::write('mm__userInfo'.json_encode($userInfo));
                //20180723mh增加短信发送
                if ($userInfo['phone'] && $smsInfo) {
                    $params = new stdClass();
                    $params->phone = $userInfo['phone'];
                    $params->module = 'nmpOrder' ;
                    $params->status = $smsInfo['status'];
                    $params->message = $smsInfo['message'];
                    $params->templateParam = $smsInfo['templateParam'];
                    log::write('mm__$params'.json_encode($params));
                    Module::callModule('phone', NULL, 'sendSms', $params);
                }
				if ($userInfo['JPUSHRegistrationID']){
                    $data_JPush['extra']['extras']['load_url'] = urldecode($url);
					R("JPush/sendJPushMessage",array('android',[$userInfo['JPUSHRegistrationID']],'registrationId',$data_JPush['alert'],$data_JPush['extra']));
				}
			}
		}
	}

	private function sendVendorNotice($vId,$serialNumber,$updateTime,$price){
		if(!$vId){return;}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$vendorModel = M("mivendor");
		Session::switchCustomer($cid);
		$TemplateModel = M("template_messages");
		$twhere['status']=array('eq',"vendorDelivering");
		$templatemsg = $TemplateModel->where($twhere)->find();
		$templateId = $templatemsg['templateId'];
		if(!$templateId){return;}
		$vendorWhere['a.id']=array('eq',$vId);
		$vendorInfo = $vendorModel->alias("a")
			->join("inner join wx_customer_user b on a.fromCustomerUserId=b.id")
			->field("b.openid")
			->where($vendorWhere)
			->find();
		if(!$vendorInfo['openid']){
			return;
		}
		$data['first'] = array('value'=> '亲，财源滚滚，您有新的订单需要处理！','color'=>'#743A3A');
		$data['keyword1'] = array('value'=> $serialNumber,'color'=>'#173177');
		$data['keyword2'] = array('value'=> $updateTime,'color'=>'#173177');
		$data['keyword3'] = array('value'=> $price,'color'=>'#173177');
		$data['remark'] = array('value'=> '1、登录后台查订单；2、快递发货；3、更改订单状态。','color'=>'#008000');
		$toUser = $vendorInfo['openid'];
		$template_id = $templateId;
		$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
			"&module=settlement&method=index";
		$url = urlencode($url);
		$topcolor = "#FF0000";
		WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
		return;
	}

	private function feyinPrint($feyinDeviceNo, $msg) {
		$arrDeviceNo = explode(",", $feyinDeviceNo);
		foreach ($arrDeviceNo as $deviceNo) {
			$freeMessage = array(
				'msgDetail' => $msg,
				'deviceNo' => $deviceNo,
			);
			Feyin::sendFreeMessage($freeMessage);
		}
	}

	public static function getMenu($tplId, $type, $sid, $userName, $rootId = NULL,$qId=null,$miUId=null,$token=null) {
		$results = Module::callModule("phone",null,"verifyPhoneCode",$token);
		$customerId = Session::$user['customerId'];
		$userId = Session::$user['userId'];					//LP修改
		$userInfo = get_UserInfo_by_fromUserName($userId);		//LP修改
		Session::switchCustomer(0);
		if ($userInfo) {
			$result["fullName"] = $userInfo[user_full_name];
			$result["phone"] = $userInfo[user_phone];
			$result["address"] = $userInfo[user_address];
		}

		$OrderModel = M("module_product_order");
		$model = M("");
		$conditionOrder["deleted"] = 0;
		$conditionOrder["type"] = $type;
		$conditionOrder["uId"] = $userId;				//LP修改
		$orderCount = $OrderModel->where($conditionOrder)->count();
		$result["orderCount"] = $orderCount;
		$param = new stdClass();
		$param->qId = $qId;
		$param->miUId = $miUId;
		if(self::isEnjoyMiPrice($param)){
			$result['isEnjoyMiPrice']=1;
		}else{
			$result['isEnjoyMiPrice']=0;
		}
		$productList = self::getCartProduct($type, $userName,null,$customerId); //侯佳修改
		$result["proSource"] =0;
		$flag=null;
		$index=0;
		$defaultDisInfo = $model->table("wx_".$customerId."_module_distribution_scheme")->where("isDefault=1")->find();
		if(!$qId&&!$miUId){
			foreach($productList as $key=>$value){
				if($value['qId']&&$value['miUid']){
					$qId=$value['qId'];
					$miUId = $value['miUid'];
					break;
				}
			}
		}

		if($productList){
			do{
				if($productList[$index]['proSource']&&!$result["proSource"]){
					$result["proSource"]=$productList[$index]['proSource'];
				}
				if(!$flag){
					if($productList[0]['distributionId']){
						$disInfo = $model->table("wx_".$customerId."_module_distribution_scheme")->where("id=".$productList[0]['distributionId'])->find();
					}else{
						$disInfo = $model->table("wx_".$customerId."_module_distribution_scheme")->where("id=".$defaultDisInfo['id'])->find();
					}
					if($disInfo['mallUrl']){
						$mllResult = self::getUrl($disInfo['mallUrl']);
						$param = $mllResult["param"];
						$param->qId = $qId;
						$param->miUId = $miUId;
						$disInfo['mallUrl'] = $mllResult["url"].urlencode(json_encode($param));
					}
					$productList[0]['distributionId']=$disInfo['id'];
					$flag["list"][]=$productList[0];
					$flag['disInfo']=$disInfo;
					array_splice($productList,0,1);
				}else{
					if($productList[$index]["distributionId"]){
						if($flag['list'][0]['distributionId']==$productList[$index]["distributionId"]&&$flag['list'][0]['activity']==$productList[$index]["activity"]&&$flag['list'][0]['logisticsStatue']==$productList[$index]['logisticsStatue']){
							$flag["list"][]=$productList[$index];
							array_splice($productList,$index,1);
						}else{
							$index++;
						}
					}else{
						if($flag['list'][0]['distributionId']==$defaultDisInfo['id']&&$flag['list'][0]['activity']==$productList[$index]["activity"]&&$flag['list'][0]['logisticsStatue']==$productList[$index]['logisticsStatue']){
							$flag["list"][]=$productList[$index];
							array_splice($productList,$index,1);
						}else{
							$index++;
						}
					}
				}
				if($index==count($productList)){
					$carList[]=$flag;
					$flag=null;
					$index=0;
				}

			}while(count($productList)>0);
		}

		$result["productList"] = $carList;
		if ($type == type_buy) {
			if (isset($rootId)) {
				$materialObjNav = self::getMaterialObj($rootId);
				if ($materialObjNav != NULL) {
					$nav = self::getNav($materialObjNav, $customerId, $userName, $rootId);
					$result["header"] = $nav["header"];
					$result["footer"] = $nav["footer"];
					$result["headerTpl"] = $nav["headerTpl"];
					$result["footerTpl"] = $nav["footerTpl"];
				}
			}
			Session::switchCustomer($customerId);
			$mallModel = M('module_mall_store');
			$mall = $mallModel->find();
			$result['mall']=$mall;
			$result['mallHue']=self::getMallHue();
			Output::instance()->module('product', 'product_multi_order_selected')->object($result);

		}
	}
	/**新增购物车数量*/
	public static function getCarNum($type,$token=NULL) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$result = Module::callModule("phone",null,"verifyPhoneCode",$token);
		$customerId = Session::$user['customerId'];
		$userName = Session::$user['userName'];
		$userId = Session::$user['userId'];
		Session::switchCustomer(0);
		$DetailModel = M("module_product_order_detail");
		Session::switchCustomer($customerId);
		$disScheeme = M("module_distribution_scheme");
		$where["oid"] = 0;
		$where["product.deleted"] = 0;
		$where["product.isRemoved"] = 0;
		$where["product.fromCustomerId"] = $customerId;
		$where["userId"] = $userId;

		$where["type"] = $type;
		$products = $DetailModel->alias("detail")
			->join("left join wx_module_product_order_detail_specification b on b.did=detail.id")
			->join("wx_module_product product ON detail.pid=product.id ")
			->where($where)
			->select();
		if($products[0]["distributionId"]){
			$distributionId = $products[0]["distributionId"];
		}else{
			$disInfo = $disScheeme->where("isDefault=1 and deleted=0")->field("id")->find();
			$distributionId = $disInfo["id"];
		}
		$list=array();
		$total=0;
		$chPrice = 0;
		$price = 0;
		foreach ($products as $product) {
			$p=new stdClass();
			$p->name=$product["name"];
			$p->pid=$product["id"];
			$p->firstSpecificName=$product["firstSpecificName"];
			$p->secSpecificName=$product["secSpecificName"];
			$p->count=$product["count"];
			$key=$product["id"];
			if($product["firstSpecificName"]){
				$key.="|".$product["firstSpecificName"];
			}
			if($product["secSpecificName"]){
				$key.="|".$product["secSpecificName"];
			}
			if($product['freeBuy']){
				$chPrice+=$product['freePrice']*$product['count'];
			}else if($product['discountedPrice']){
				$chPrice+=$product['discountedPrice']*$product['count'];
			}else{
				$chPrice+=$product['fixedPrice']*$product['count'];
			}
			if($product['discountedPrice']){
				$price+=$product['discountedPrice']*$product['count'];
			}else{
				$price+=$product['fixedPrice']*$product['count'];
			}
			$p->key=$key;
			$list[$key]=$p;
			$total+=$p->count;
		}
		$out=new stdClass();
		$out->total=$total;
		$out->list=$list;
		$out->chPrice = $chPrice;
		$out->price = $price;
		$out->distriScheme = $distributionId;
		$result["total"] =$total;
		$result["chPrice"] = $chPrice;
		Output::instance()->object($out);
	}
	public static function getCart($type, $sid, $userName, $rootId,$token=NULL) {
		$result = Module::callModule("personCenter",null,"verifyToken",$token);

		$customerId = Session::$user['customerId'];
		if (isset($rootId)) {
			$materialObjNav = self::getMaterialObj($rootId);
			if ($materialObjNav != NULL) {
				$nav = self::getNav($materialObjNav, $customerId, $userName, $rootId);
				$result["header"] = $nav["header"];
				$result["footer"] = $nav["footer"];
				$result["headerTpl"] = $nav["headerTpl"];
				$result["footerTpl"] = $nav["footerTpl"];
			}
		}
		$customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
		$result["productList"] = self::getCartProduct($type, $userName,null);
		$result["total"] = count($result["productList"]);
		Output::instance()->module('product', 'product_common_cart')->object($result);
	    Session::switchCustomer($customerId);
	}

	/**
	 * 获取商品列表
	 * @param $pids		/商品ids
	 * @param null $counts
	 * @param null $deposits
	 * @param string $teamBuyType
	 * @param null $sizes
	 * @param null $colors
	 * @return array
	 */
	private static function getPreSubmitOrderProduct($pids, $counts=null,$deposits=NULL,$teamBuyType="now",$sizes=null,
													 $colors=null,$type=null) {
		$arrCondition = array();
		$arrPid = explode(",", $pids);
		$sizes = explode(",", $sizes);
		$colors = explode(",", $colors);
		if($counts!= null) $arrCount = explode(',', $counts);
		if($deposits!= null) $arrDeposit = explode(',', $deposits);
		$customerId= Session::$user['customerId'];
		Session::switchCustomer(0);
		$form_tab = M('form');
		$ProductModel = M("module_product");
		$productSpec=M("module_product_specification");
		$pointScheme_tab = M('module_point_scheme');
		Session::switchCustomer($customerId);
		$productList = array();
		$cardCount = 0;
		foreach ($arrPid as $k=>$pid) {
			if($type == ORDER_TYPE_FORM){
				$where['a.id'] = intval($pid);
				$arr = $form_tab->alias("a")
					->join("left join wx_mishare b on a.id=b.moduleId and b.module='micontent'")
					->join("left join wx_module_point_scheme c on a.pointSchemeId=c.id and c.deleted=0")
					->field("a.id, a.formName as name,a.type as isPay,a.vendorId as vId,a.payPrice as price,a.supplyPrice,a.platCut,a.saleCut,
					a.pointSchemeId, b.id as sid, c.property, c.name as schemeName")
					->where($where)->find();
				if(!$arr['pointSchemeId']){
					$pointSchemeInfo = $pointScheme_tab->where(['cid' => $customerId, 'default' => 1, 'status' => 1, 'deleted' => 0])->find();
					$arr['pointSchemeId'] = $pointSchemeInfo['id'];
					$arr['schemeName'] = $pointSchemeInfo['name'];
					$arr['property'] = $pointSchemeInfo['property'];
				}
				if($arr !== null){
					$arr['orderType'] = ORDER_TYPE_FORM;
				}
			}else{
				$where['pdt.id'] = intval($pid);
				$arr = $ProductModel->alias("pdt")
					->join("left join wx_mishare b on pdt.id=b.moduleId	and b.module='product'")
					->field("pdt.*,b.id as sid")
					->where($where)->find();
			}
			if($arr['rechargeableCard'] == 1) {
				$cardCount++;
			}
			if($arrCount){
				$arr['reserveCount'] = $arrCount[$k];
				$arr['freePrice']=$arrDeposit[$k];
				$arr['teamBuyType']=$teamBuyType;
			}
			if($arr['isChainPro']){
				$where['pdt.id'] = intval($arr['supplyProId']);
				$supplyProInfo = $ProductModel->alias("pdt")->where($where)->find();
				$arr['supplyPrice']=$supplyProInfo['supplyPrice'];
				$arr['channelSupplyPrice']=$supplyProInfo['channelSupplyPrice'];
				$arr['serialNumber']=$supplyProInfo['serialNumber'];
				$arr['inventory']=$supplyProInfo['inventory'];
				$arr['inventoryCount']=$supplyProInfo['inventoryCount'];
				$arr['vId']=$supplyProInfo['vId'];
			}
			if($arr['supportSpecification']==1){
				$spcWhere["pid"]=array("eq",$pid);
				$spcWhere["firstSpecificName"]=array("eq",$sizes[$k]);
				$colors[$k]?$spcWhere["secSpecificName"]=array("eq",$colors[$k]):"";
				$priceInfo = $productSpec->where($spcWhere)->find();
				$arr['fixedPrice']=$priceInfo['fixedPrice'];
				$arr['discountedPrice']=$priceInfo['discountedPrice'];
				$arr['platCut']=$priceInfo['platCut'];
				$arr['saleCut']=$priceInfo['saleCut'];
				$arr['miPrice']=$priceInfo['miPrice'];
				$arr['serialNumber']=$priceInfo['serialNumber'];
				$arr['weight']=$priceInfo['weight'];
				$arr['customsName']=$priceInfo['customsName'];
				$arr['customsPrice']=$priceInfo['customsPrice'];
				$arr['supplyPrice']=$priceInfo['supplyPrice'];
				$arr['channelSupplyPrice']=$priceInfo['channelSupplyPrice'];
				$arr['tariff']=$priceInfo['tariff'];
				$arr['supplierSkuNo']=$priceInfo['supplierSkuNo'];
				$arr['firstSpecificUnit']=$priceInfo['firstSpecificUnit'];
				$arr['secSpecificUnit']=$priceInfo['secSpecificUnit'];
				$arr['seckillPrice']=$priceInfo['seckillPrice'];
				$arr['seckillSalce']=$priceInfo['seckillSalce'];
				if($arr['isChainPro']){
					$spcWhere["pid"]=array("eq",$arr['supplyProId']);
					$supplyProInfo = $productSpec->where($spcWhere)->find();
					$arr['supplyPrice']=$supplyProInfo['supplyPrice'];
					$arr['channelSupplyPrice']=$supplyProInfo['channelSupplyPrice'];
					$arr['serialNumber']=$supplyProInfo['serialNumber'];
				}
			}
			array_push($productList, $arr);
		}
		if ($cardCount > 0 && $cardCount != count($productList)) {//有充值卡商品并且还有其他商品
			return false;
		}
		return $productList;
	}

	/**
	 * 获取订单的详情信息
	 * @param $oid	/订单id
	 * @param $orderType	/订单类型
	 * @return mixed
	 */
	private static function getSubmitOrderProduct($oid, $orderType=0) {
		$customerId = Session::$user['customerId'];
		$DetailModel = M("module_product_order_detail");
		if(strstr($oid, ',')){
			$where["oid"] = array('in', $oid);
		}else{
			$where["oid"] = $oid;
		}

		$where["product.deleted"] = 0;
		if($orderType == ORDER_ORDERTYPE_NINE){
			$productList = $DetailModel->where(['oid'=>$oid])->select();
		}else{
			$productList = $DetailModel->alias("detail")->where($where)
				->join("wx_module_product product ON detail.pid=product.id ")
				->field("product.*, detail.count as reserveCount,detail.freePrice")
				->select();
		}
		if(count($productList)<1){
			Log::write('getProductList---'.$DetailModel->getLastSql());
		}
		// 		echo $DetailModel->getLastSql();
		return $productList;
	}

	private static function getCartProduct($type, $userName,$dids,$cid = ''){
		//侯佳添加
		if (!empty($cid)) {
			$customerId = $cid;
			$where['product.fromCustomerId'] = $customerId;
		} else {
			$customerId = Session::$user['customerId'];
		}

		$userId = Session::$user['userId'];
		Session::switchCustomer(0);
		$DetailModel = M("module_product_order_detail");
		$productSpec=M("module_product_specification");
		$productModel = M("module_product");
		$orderSpecModel = M('module_product_order_detail_specification');
		Session::switchCustomer($customerId);
		$where["oid"] = 0;
		$where["product.deleted"] = 0;
		$where["product.isRemoved"] = 0;
		if($dids){
			$where["detail.id"] = array('in', $dids);
		} else {
			$where["userId"] = $userId;
			$where["type"] = $type;
		}
		$productList = $DetailModel->alias("detail")->where($where)
			->join("wx_module_product product ON detail.pid=product.id ")
			->join("wx_mishare a on product.id=a.moduleId and a.module='product' and a.cid is null")
			->field("product.*, detail.count as reserveCount, detail.id as did,detail.sId,
			detail.freePrice,detail.qId,detail.miUid,detail.price,a.id as sid,detail.playType as detailPlayType,detail.customizedInfo")
			->select();
		$proSource = 0;
		foreach($productList as $k=>$v){
			//$discount = self::getDiscountPrice($v['id']);
			//$productList[$k]["discountedPrice"]=$discount['discPrice'];
			if($v['picUrl1']){
				$productList[$k]['picUrl1']=json_decode($v['picUrl1'],true);
			}
			if($v['supportSpecification'] == '1'){
				$orderSpecWhere['did'] = $v['did'];
				$spec = $orderSpecModel->where($orderSpecWhere)->find();
				$productList[$k]['firstSpecName'] = $spec['firstSpecificName'];
				$productList[$k]['secondSpecName'] = $spec['secSpecificName'];
				$spcWhere=null;
				$spcWhere["pid"]=array("eq",$v['id']);
				$spcWhere["firstSpecificName"]=array("eq",$spec['firstSpecificName']);
				$spec['secSpecificName']?$spcWhere["secSpecificName"]=array("eq",$spec['secSpecificName']):"";
				$priceInfo = $productSpec->where($spcWhere)->find();
				$productList[$k]['fixedPrice']=$priceInfo['fixedPrice'];
				$productList[$k]['discountedPrice']=$priceInfo['discountedPrice'];
				$productList[$k]['platCut']=$priceInfo['platCut'];
				$productList[$k]['saleCut']=$priceInfo['saleCut'];
				$productList[$k]['miPrice']=$priceInfo['miPrice'];
				$productList[$k]['serialNumber']=$priceInfo['serialNumber'];
				$productList[$k]['weight']=$priceInfo['weight'];
				$productList[$k]['customsName']=$priceInfo['customsName'];
				$productList[$k]['customsPrice']=$priceInfo['customsPrice'];
				$productList[$k]['tariff']=$priceInfo['tariff'];
				$productList[$k]['seckillPrice']=$priceInfo['seckillPrice'];
				$productList[$k]['seckillSalce']=$priceInfo['seckillSalce'];
				$specModel = m('module_product_specification');
				if($v['isChainPro']){
					$spcWhere["pid"]=array("eq",$v['supplyProId']);
					$supplyProInfo = $productSpec->where($spcWhere)->find();
					$vId = $productModel->where("id=".$v['supplyProId'])->getField("vId");
					$productList[$k]['supplyPrice']=$supplyProInfo['supplyPrice'];
					$productList[$k]['channelSupplyPrice']=$supplyProInfo['channelSupplyPrice'];
					$productList[$k]['serialNumber']=$supplyProInfo['serialNumber'];
					$productList[$k]['specCount'] = $supplyProInfo['inventoryCount'];
					$productList[$k]['vId'] = $vId;
				}else{
					$productList[$k]['supplyPrice']=$priceInfo['supplyPrice'];
					$productList[$k]['channelSupplyPrice']=$priceInfo['channelSupplyPrice'];
					$productList[$k]['specCount'] = $v['inventoryCount'];
				}
			}else{
				$productList[$k]['firstSpecName'] = null;
				$productList[$k]['secondSpecName'] = null;
				$productList[$k]['specCount'] = null;
				if($v['isChainPro']){
					$supplyProInfo = $productModel->where("id=".$v['supplyProId'])->find();
					$productList[$k]['supplyPrice'] = $supplyProInfo["supplyPrice"];
					$productList[$k]['channelSupplyPrice'] = $supplyProInfo["channelSupplyPrice"];
					$productList[$k]['serialNumber'] = $supplyProInfo["serialNumber"];
					$productList[$k]['inventory'] = $supplyProInfo["inventory"];
					$productList[$k]['vId'] = $supplyProInfo['vId'];
				}
			}
			$productList[$k]['freePrice'] = $v["freePrice"];
		}
//		var_dump($productList);
		return $productList;
	}

	private static function getCartPoints($type, $sid, $userName) {
		$customerId = Session::$user['customerId'];
		$DetailModel = M("module_product_order_detail");
		$conditionDetail["oid"] = 0;
		$conditionDetail["fromUserName"] = $userName;
		$conditionDetail["type"] = $type;
		$conditionDetail["storeId"] = $sid;
		$points = $DetailModel->alias("detail")->where($conditionDetail)
			->join("wx_module_product product ON detail.pid=product.id")
			->sum('product.points');
// 				echo $DetailModel->getLastSql();
		return $points;
	}

	private static function getCartPrice($type, $sid, $userName) {
		$customerId = Session::$user['customerId'];
		$DetailModel = M("module_product_order_detail");
		$conditionDetail["oid"] = 0;
		$conditionDetail["fromUserName"] = $userName;
		$conditionDetail["type"] = $type;
		$conditionDetail["storeId"] = $sid;
		$price = $DetailModel->alias("detail")->where($conditionDetail)
			->join("wx_".$customerId."_module_product product ON detail.pid=product.id")->sum('product.price');
		// 				echo $DetailModel->getLastSql();
		return $price;
	}

	/*
	 * 获取商品应支付金额
	 * productList:商品列表
	 * counts:用户选择数量,NULL时从商品列表的reserveCount获取
	 * oid: 订单id,将订单中的商品价格更新为当前提交时的价格,NULL时不更新订单数据
	 *
	 */
	private static function getProductPay($productList, $counts = NULL, $oid = NULL,$isEnjoyMiPrice=0) {
		$price = NULL;
		$points = 0;
		$priceFree=NULL; //自由购商品总价
		$i = 0;
		if ($counts) {
			$arrCount = explode(",", $counts);
		}
		if ($oid) {
			$DetailModel = M("module_product_order_detail");
		}
		$vendorPrice = array();
		foreach ($productList as $product) {
			if (isset($product["reserveCount"])) {
				$reserveCount = $product["reserveCount"];
			} else if ($arrCount && $arrCount[$i]) {
				$reserveCount = $arrCount[$i];
			} else {
				$reserveCount = 0;
			}
			$tempType = type_buy;

			/*侯佳2018-02-13添加，计算支付总积分*/
			if ($product['points'] == null) {
				$points--;
			} else {
				$points = $points + $product['points'] * $counts;
			}
			/*侯佳2018-02-13添加，计算支付总积分*/

			//原价
	       if ($product["fixedPrice"] !== NULL&&$product["fixedPrice"]>=0) {
	           $tempPrice = $product["fixedPrice"] * $reserveCount;
	           $temp1Price = $product["fixedPrice"] * $reserveCount;
	           $detailPrice=$product["fixedPrice"];
	       }
			//打折价
	       if ($product["discountedPrice"] !== NULL&&$product["discountedPrice"]>0) {
	           $tempPrice = $product["discountedPrice"] * $reserveCount;
	           $temp1Price = $product["discountedPrice"] * $reserveCount;
	           $detailPrice=$product["discountedPrice"];
	       }
			if($product["playType"]==6){//夺宝产品
				$result["playType"]=6;
			}
	       if($product["freeBuy"]) { //自由购
		       $temp1Price = $product["freePrice"] * $reserveCount;
		       $detailPrice1=$product["freePrice"];
		       $result["freebuy"]=1;
		   }
			//团购
		   if($product["teambuy"]&& $product["teamBuyType"]=="team") { //团购
		       $tempPrice = $product["teamPrice"] * $reserveCount;
	           $detailPrice=$product["teamPrice"];
		       $result["teambuy"]=1;
		   }
			//玩法
			if($product["playType"]==3){//夺宝产品
				$tempPrice = $product["perMoney"]*$reserveCount;
				$detailPrice = $product["perMoney"];
				$result["playType"]=3;
			}
			if($product['playType']==5&&$isEnjoyMiPrice){
				$tempPrice = $product["miPrice"]*$reserveCount;
				$detailPrice = $product["miPrice"];
				$result["playType"]=5;
			}
			//操作库存时需要判断下单时已哪个价格购买新增订单类型 7 秒杀订单  由于4被密友加入订单占用
			$json = json_decode($product['json'],true);
			if($product['playType']==4&&strtotime($json['seckillStartTime'])<time()&&strtotime($json['seckillEndTime'])>time()){
				$tempPrice = $product["seckillPrice"]*$reserveCount;
				$detailPrice = $product["seckillPrice"];
				$result["playType"]=7;
			}
			if($product['activity']==1){
				$result["isActivity"]=1;
			}
			if($product['price']){
				$tempPrice = $product["price"]*$reserveCount;
			}

			/*form 营销订单*/
			if($product['orderType'] == ORDER_TYPE_FORM){
				$tempPrice = $product["price"]*$reserveCount;
				if(!$tempPrice){
					$tempPrice = 0;
				}
			}
		   if($product["virtual"]) { //虚拟
		       $result["virtual"]=1;
		   }
			$vId = null;
			$isHas = false;
			foreach($vendorPrice as $key=>$value){
				if($value["vId"]==$product["vId"]){
					$vId=$key;
					$isHas=true;
				}
			}
			if($isHas){
				$vendorPrice[$vId]["price"]+=$tempPrice;
			}else{
				$temp["vId"]=$product["vId"];
				$temp["isChainPro"]=$product["isChainPro"];
				$temp["supplyChainId"]=$product["supplyChainId"];
				$temp["price"]=$tempPrice;
				if($product['orderType'] == ORDER_TYPE_FORM){
					$temp['isPay'] = $product['isPay'];
				}
				array_push($vendorPrice,$temp);
			}
		   if ($price == NULL) {
		       $price = $tempPrice;
		   } else {
		       $price += $tempPrice;
		   }
		   if ($priceFree == NULL) {
		       $priceFree = $temp1Price;
		   } else {
		       $priceFree += $temp1Price;
		   }
		   if ($price=== NULL) {
				Output::instance()->resultCode(code_product_pay_invalid);
				return;
		   }
			if (!isset($payType)) {
				$payType = $tempType;
			}
			if ($payType !== $tempType) {
				Output::instance()->resultCode(code_product_pay_different);
				return;
			}
			if ($oid) {
				$conditionDetail = array();
				if(strstr($oid,",")){
					$conditionDetail["oid"] = array("in",$oid);
				}else{
					$conditionDetail["oid"] = $oid;
				}

				$conditionDetail["pid"] = $product["id"];
				if ($tempType == type_buy && isset($tempPrice)) {
					$dataDetail["price"] = $detailPrice;
					$dataDetail["freePrice"] = $detailPrice1;
				} else if (isset($tempPoints)) {
					$dataDetail["points"] = $tempPoints;
				} else {
					Log::write('set order detail pay error' . $tempType);
				}
				// $dataDetail['levelId'] = $tempDiscount['levelId'];
				// $dataDetail['levelName'] = $tempDiscount['levelName'];
				// $dataDetail['activityId'] = $tempDiscount['activityId'];
				// $dataDetail['activityName'] = $tempDiscount['activityName'];
				// $dataDetail['buyDiscountPrice'] = $tempDiscount['discPrice'];
				$DetailModel->where($conditionDetail)->save($dataDetail);
			}
			$i++;
		}
		$username = Session::$user['userName'];
		// $MemberModel = M("member");
		// $customerId = Session::$user['customerId'];
		// $condition['member.fromUserName'] = array('eq',$username);
		// $level = $MemberModel->alias('member')
		// 	->join("LEFT JOIN  wx_member_object object ON member.objectId = object.id")
		// 	->join("LEFT JOIN  wx_member_object_level level ON member.objectLevelId = level.id")
		// 	->join("LEFT JOIN  wx_member_uni_user_info info ON member.fromUserName = info.fromUserName")
		// 	->where($condition)
		// 	->field('level.`id`, level.`name`')
		// 	->find();

		$result["type"] = $tempType;
		$result["price"] = $price;
		$result["points"] = $points;
		$result["priceFree"]=$priceFree;
		$result["vendorPrice"]=$vendorPrice;
		// $result['levelId'] = $level['id'];
		// $result['levelName'] = $level['name'];
		return $result;
	}

	private static function getLastOrderPay($ids, $type) {
		$OrderModel = M("module_product_order");
		$where["id"] = $ids;
		$order=$OrderModel->where($where)->find();
		$fieldName="price";
		if($order["freebuy"]) {
			$fieldName="deposit";
		}
		$pay = $OrderModel->where($where)->getField($fieldName);
		return $pay;
	}

	/**
	 * @todo [获取订单列表]
	 * @param $tplId
	 * @param $type [固定写法 buy,point],  营销订单传form
	 * @param $userName
	 * @param $start
	 * @param $limit
	 * @param int $status [0-5,0-代付款,1-代发货,2-已发货,3-交易成功,4-退款,5-快捷订单]
	 * @param bool|false $isNotSubmit [是否过滤掉为提交订单]
	 * @param null $rootId
	 * @param null $vId
	 * @param string $order
	 * @param string $orderBy
	 * @param string $search	/订单号搜索
	 */
	public static function getOrder($tplId, $type, $userName, $start, $limit,$status=0, $isNotSubmit = false,
									$rootId = NULL, $search = NULL, $token = NULL, $order = 'updateTime', $orderBy = 'desc') {
		$customerId = Session::$user['customerId'];
		$userId = Session::$user['userId'];
		$token = Module::callModule("personCenter",null,"verifyToken",$token);
		if (isset($rootId)) {
			$materialObjNav = self::getMaterialObj($rootId);
			if ($materialObjNav != NULL) {
				$nav = self::getNav($materialObjNav, $customerId, $userName, $rootId);
				$result["header"] = $nav["header"];
				$result["footer"] = $nav["footer"];
				$result["headerTpl"] = $nav["headerTpl"];
				$result["footerTpl"] = $nav["footerTpl"];
			}
		}

 		Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		Session::switchCustomer($customerId);
		$arrCondition = array();
		$arrType = explode(",", $type);
		foreach ($arrType as $type) {
			array_push($arrCondition, array('eq', $type));
		}
		array_push($arrCondition, 'or');

		if ($isNotSubmit) {
			$whereOrder["pod.status"] = array('neq', order_status_notsubmit);
		}
		$pageStart=$start*$limit;
		$whereOrder["pod.deleted"] = 0;
		$whereOrder["pod.type"] = $arrCondition;
		// $userName = 'o7pYBuKvlJxvhY9nhD24aeekuDcQ';//测试用
//		$whereOrder["pod.fromUserName"] = $userName;
		$whereOrder["pod.uId"] = $userId;						//Lp修改
		$whereOrder["pod.fromCustomerId"] = $customerId;

		$whereOrder["pod.module"] = array('EXP','IS NULL');
		if($search){
			$whereOrder["pod.serialNumber"] = ['like', '%'.$search.'%'];
		}
		if($type == ORDER_TYPE_FORM){
			$whereOrder['pod.type'] = ORDER_TYPE_FORM;
			unset($whereOrder["pod.module"]);
		}elseif ($type == ORDER_TYPE_POINT) {//增加积分订单，侯佳2018-03-02
			$whereOrder['pod.type'] = ORDER_TYPE_POINT;
		} elseif ($type == type_buy) {
			$whereOrder['pod.type'] = type_buy;
		}
		switch($status){
			case 0:
				$whereOrder["pod.status"]=array(array("eq",order_status_notsubmit),array("eq","paying"),array("eq","teaming"),'or');
				break;
			case 1:
				$whereOrder["pod.status"]=array(array("eq",order_status_delivering),array("eq",order_status_deliveringtostore),array("eq",order_status_paypart),array("eq",order_status_ordersign),array("eq","supported"),"or");
				if($type == 'form'){
					$whereOrder["pod.status"]=array(array("eq",order_status_delivering),array("eq","submission"),"or");
				}
				break;
			case 2:
				$whereOrder["pod.status"]=array(array("eq",order_status_delivered),array("eq",order_status_deliveredtostore),"or");
				break;
			case 3:
				$whereOrder["pod.status"]=array(array("eq",order_status_ok),array("eq",order_status_confirmsign),'or');
				break;
			case 4:
				$whereOrder["_string"] ="pod.status='".order_status_refund."' or pod.status='".ORDER_STATUS_REFUNDEDPART."' or pod.status='".ORDER_STATUS_REFUNDING."'";
				break;
			case 5:
				$whereOrder["pod.status"] = order_status_cancel;
				break;
		}

		$arr = $OrderModel->alias("pod")->where($whereOrder)
			->join("inner join wx_module_product_order_detail detail on pod.id=detail.oid")
			//->join("wx_store_resource_base base ON pod.storeResourceId= base.id")
			//->join("wx_store store ON store.id = pod.storeId")
			->field("pod.*,sum(detail.count) as totalCount")
			->order("$order $orderBy")
			->group("pod.id")
			->limit($pageStart, $limit)->select();

		Log::write( $OrderModel->getLastSql());
		$count =$OrderModel->alias("pod")->where($whereOrder)
			->join("inner join wx_module_product_order_detail detail on pod.id=detail.oid")
			->count("pod.id");

		foreach($arr as $k => $v){
			if($v['serialNumber'] != null && $v['separatedId'] != null){
				$arr[$k]['serialNumber'] = "{$v['serialNumber']}_{$v['separatedId']}";
			}
		}
		foreach($arr as $k => $v){
				$arr[$k]['OrderDetailInfo'] = self::getOrderDetailInfo($v['id'], $userName,-1, $type);
			//	$arr[$k]['getOrderDetail'] = self::getOrderDetail($tplId, $v['id'],$sid, $isShare, $type, $rootId = NULL,$noNeedJsonResult=true);

		}
	//	getOrderDetail($tplId, $id,$sid, $isShare, $type, $rootId = NULL,$noNeedJsonResult=true)

		$result["total"] = $count;
		$result["results"] = $arr;
		$result['mallHue']=self::getMallHue();
		$result["pageCount"]=getPageCount($count,$limit);
		Output::instance()->module('product', 'product_common_order')->object($result);
	}



	public static function getOrderDetailInfo($ids, $fromUserName,$sid, $type){
		$customerId = Session::$user['customerId'];
		//$result["orderCount"] = 1;
		$idArray = explode(',', $ids);
		$productList = array();
		Session::switchCustomer(0);
		$DetailModel = M("module_product_order_detail");
		foreach ($idArray as  $k => $v) {
			$condition["detail.oid"] = $v;
//			$condition["detail.fromUserName"] = $fromUserName;//Lp修改
			$productList = $DetailModel->alias("detail")->where($condition)
				->join("wx_module_product_order_detail_specification spec ON spec.did=detail.id")
				->field("detail.pid as id,detail.name,detail.fixedPrice,detail.discountedPrice,
				detail.picUrl,detail.picUrl1,detail.price,detail.points,detail.freePrice,detail.count as reserveCount,
				 spec.firstSpecificName as sizeName, spec.secSpecificName as colorName,detail.sId,detail.customizedInfo")
				->select();
			foreach($productList as $key => $product){
				$comment = self::getUserComment($v,$product['id'],$fromUserName);
				$productList[$key]['isComment']=$comment;
				if($product['picUrl1']){
					$productList[$key]['picUrl1'] =json_decode($product['picUrl1'],true);
				}
				if($product['customizedInfo']){
					$productList[$key]['customizedInfo'] = json_decode($product['customizedInfo'], true);
				}
			}
		}
		Session::switchCustomer($customerId);
		return $productList;
	}

	public function getUserComment($oid,$pid,$fromUserName,$did){
		$ProductCommentModel=M("module_product_comment");
        $orderModel = M("module_product_order");
        $orderDetailModel = M("module_product_order_detail");
        $commentConfig = M("module_comment_config");
		$condition["oid"]=array('eq',$oid);
		$condition["pid"]=array('eq',$pid);
        $condition["type"]=array('eq',0);
		$condition["fromUserName"]=array('eq',$fromUserName);
        $orderInfo = $orderModel->where("id=$oid")->field("status,completionTime,fromCustomerId")->find();
        $configInfo = $commentConfig->where("customerId=".$orderInfo['fromCustomerId'])->find();
        $completionTime = strtotime($orderInfo['completionTime']);
        $day = $configInfo['validityDays'];
        $now = date("Y-m-d H:i:s");
        $now = strtotime("$now -$day day");
        if($orderInfo['status']!=order_status_ok||$now>$completionTime){
            return 2;
        }
        $productInfo = $orderDetailModel
            ->where("id=$did")
            ->field("price,count")
            ->find();
        if($productInfo['price']*$productInfo['count']<=$configInfo['singleProductAmount']){
            return 2;
        }
		$result=$ProductCommentModel->where($condition)->find();
		if($result && count($result) > 0){
			return 1;
		} else  {
			return 0;
		}
	}
	public static function getOrderInfo($id, $fromUserName,$type,$sid="",$notUse=0,$token){
		$customerId = Session::$user['customerId'];
		if(strstr($id,",")){
			$whereOrder["a.id"] = array("in",$id);
		}else{
			$whereOrder["a.id"] = array("eq",$id);
		}
		$VerifyCode = M("module_verify_code");
		Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		$DetailModel = M("module_product_order_detail");
		$order = $OrderModel->alias("a")
			->join("left join wx_module_user_coupon b on a.userCouponId=b.id")
			->join("left join wx_module_coupon c on b.couponId=c.id")
			->field("a.*,c.money")
			->where($whereOrder)->select();
		if (!$order) {
			Output::instance()->resultCode(code_product_order_not_exist);
			return;
		}
		if (count($order) > 1) {
			$result['payType'] = $order[0]['payType'];
			$result['deliveryType'] = $order[0]['deliveryType'];
			$result['status'] = $order[0]['status'];
			$result['type'] = $order[0]['type'];
			$result['price'] = $OrderModel->alias("a")->where($whereOrder)->getField('SUM(a.price) as price');
			$result['points']  = $OrderModel->alias("a")->where($whereOrder)->getField('SUM(a.points) as points');
			$result["storeId"] = $order[0]['storeId'];
			$result["expressName"] =urlencode($order[0]['expressName']);
			$result["expressName1"] =$order[0]['expressName'];
			$result["createTime"] = $order[0]['createTime'];
			$result["isActivity"]=$order[0]['isActivity'];
		} else {
			$result = $order[0];
			$result["expressName"] =urlencode($order[0]['expressName']);
			$result["expressName1"] =$order[0]['expressName'];
			$result["isActivity"]=$order[0]['isActivity'];
		}
		$result['proSource']=0;
		foreach($order as $key=>$value){
			if($value['proSource']==1){
				$result['proSource']=1;
				break;
			}
		}
		$result['storeResourceId'] = $order[0]['storeResourceId'];
		$result['storeResourceName'] = $order[0]['storeResourceName'];
		$result["distributionId"] = $order[0]['distributionId'];
		//判断下单时间
		$createTime = strtotime($result["createTime"]." + 10 min")-time();
		if($createTime<=0){
			$result["canPay"]=0;
		}else{
			$result["canPay"]=1;
			$result["payTime"] = date("i:s",$createTime);
		}
//		if ($result['price'] && $result['points']) {
//			Output::instance()->resultCode(code_product_pay_different);
//			return;
//		}
		if($result["isVirtual"]=="1") {
			$verifyCode=$VerifyCode->where("oid in ($id)")->select();
			if($verifyCode) {
				$result["verifyCode"]=$verifyCode;
			}
		}
		$productList = array();
		$DetailModel = M("module_product_order_detail");
		$id = explode(',',$id);
		foreach($id as $index=>$value){
			$condition["detail.oid"] = $value;
			if($id && $id=="0") {
				$condition["od.fromUserName"] = $fromUserName;
			}
			$product= $DetailModel->alias("detail")->where($condition)
				->join("wx_module_product product ON detail.pid=product.id")
				->join("wx_module_product_order_detail_specification spec ON spec.did=detail.id")
				->field("product.id, product.rechargeableCard, product.logisticsStatue,detail.name,detail.fixedPrice,detail.discountedPrice,detail.picUrl
				,detail.picUrl1,detail.oid,detail.price,detail.points,detail.freePrice,detail.count as reserveCount,
				spec.firstSpecificName as sizeName, spec.secSpecificName as colorName,detail.sId,
				detail.pid,detail.shareFromGuid,detail.customizedInfo,detail.customizedDescription3,detail.squarePicUrl,detail.id as did")
				->select();
			$count = $DetailModel->alias("detail")->where($condition)->field("sum(count) as count")->find();
			foreach($product as $key => $pro){
				$comment = self::getUserComment($value,$pro['id'],$fromUserName,$pro['did']);
				$product[$key]['isComment']=$comment;
				$product[$key]["totalCount"]=$count['count'];
				if($pro["picUrl1"]){
					$product[$key]['picUrl1'] = json_decode($pro['picUrl1'],true);
				}
				$product[$key]['customizedInfo'] = json_decode($pro['customizedInfo'],true);
			}
			$result['logisticsStatue'] = $product[0]['logisticsStatue'];
			$productList[$value]["list"] = $product;
			$canUserList = self::getCouponList($order[$index]['id'],null,null,null,$token,1,$customerId);
			if(!$order[$index]['userCouponId']&&!$order[$index]['wxTransactionId']){
				if($canUserList[$index]&&!$notUse){
					$order[$index]['userCouponId']=$canUserList[$index]['userCouponId'];
					$order[$index]['money']=$canUserList[$index]['money'];
				}
			}
			$productList[$value]["orderInfo"] = $order[$index];
			$canUserList?$productList[$value]['haveUserCoupon'] =true:$productList[$value]['haveUserCoupon'] =false;
		}

		Session::switchCustomer($customerId);
		$result["productList"] = $productList;
		return $result;
	}

	/**
	 * 个人中心获取订单详情
	 * @param $tplId
	 * @param $id
	 * @param $sid
	 * @param $isShare
	 * @param $type
	 * @param null $rootId
	 * @param bool $noNeedJsonResult
	 * @param int $notUse
	 */
	public static function getOrderDetail($tplId, $id,$sid, $isShare, $type, $rootId = NULL,$noNeedJsonResult=true,$notUse=0,$token) {
		$userName = Session::$user['userName'];
		$customerId = Session::$user['customerId'];
		$userId = Session::$user['userId'];
		$mallModel=M("module_mall_store");
		Session::switchCustomer(0);
		$productModel = M('module_product');
		$storeModel = M("store");
		$couponScheme = M("module_coupon_scheme");
		$orderModel = M("module_product_order");
		$orderDetail = M("module_product_order_detail");
		$purseModel = M("module_user_purse");
		$pointModel = M('module_user_point');
		Session::switchCustomer($customerId);
		$userModel = M('user');
		$userAddress = M("user_receiver_address");
		///获取order信息
		$result = product::getOrderInfo($id, $userName,$sid, $type,$notUse,$token);
		$couponMoney = 0;
		$cardCount = 0;
		foreach($result['productList'] as $key=>$value){
			$couponMoney+=$value['orderInfo']['money'];
			if ($value['list'][0]['rechargeableCard'] == 1) {
				$cardCount++;
			}
		}
		$result['couponMoney']=$couponMoney;
		$mallResult=$mallModel->find();
		if (!isset($result)) {
			return;
		}
		$result['mallHue']=self::getMallHue();
		$result["mall"]=$mallResult;
		$result['browser']=isMicroMessengerUserAgent()?1:0;
		$userId = Session::$user['userId'];
		$purseWhere1 = [
			'userId'    => $userId,
			'cid'       => $result['fromCustomerId']
		];
		$balance = $purseModel->where($purseWhere1)->getField("balance");//获取用户钱包余额
		(empty($balance)) ? $balance = 0.00:'';
		$payPassword = $userModel->where("id = $userId")->getField('payPassword');//获取支付密码
		if (empty($payPassword)) {//未设置支付密码
			$payPassword = 0;
		} else {                  //已设置支付密码
			$payPassword = 1;
		}
		$result['balance'] = $balance;
		$result['payPassword'] = $payPassword;
		unset($balance);

		$detailWhere['oid'] = $id;
		$orderDetail1 = $orderDetail->where($detailWhere)->select();  //获取订单的详细信息
		$prosType = [];
		$cardCount = 0;
		foreach ($orderDetail1 as $item) {
			$pid = $item['pid'];
			$rechargeableCard = $productModel->where("id = $pid")->getField('rechargeableCard');
			$proType['proId'] = $pid;
			if ($rechargeableCard == 1) {
				$proType['rechargeableCard'] = 1;
				$cardCount++;
			} else {
				$proType['rechargeableCard'] = 0;
			}
			array_push($prosType, $proType);
		}
		$result['proRechargeableCard'] = $prosType;

		if ($tplId == 0) {
			if(!$noNeedJsonResult){
				return $result;
			}
			if($result['type'] == 'form'){
				$formPayInfo = R('Mall/getPayAndLogisticsList',
					array(0, 0, $result['payType'], null, $customerId,null));
				unset($formPayInfo['shipping']);
				unset($formPayInfo['deliveryHasDefault']);
				$result['payInfo'] = $formPayInfo;
				Output::instance()->module('product', 'product_common_formOrder_detail')->object($result);
			}else if (!$isShare) {
				Output::instance()->module('product', 'product_order_detail')->object($result);
			} else {
				Output::instance()->module('product', 'product_order_detail_share')->object($result);
			}
			return;
		} else {
			if (isset($rootId)) {
				$materialObjNav = self::getMaterialObj($rootId);
				if ($materialObjNav != NULL) {
					$nav = self::getNav($materialObjNav, $customerId, $userName, $rootId);
					$result["header"] = $nav["header"];
					$result["footer"] = $nav["footer"];
					$result["headerTpl"] = $nav["headerTpl"];
					$result["footerTpl"] = $nav["footerTpl"];
				}
			}
			//获取最后一次自提门店id
			$userInfo = get_UserInfo_by_fromUserName($userId);																//LP修改
			//获取收货人默认收货地址
//			$useraddress = get_User_Address_fromUserName($userName);
//			dump($userInfo);exit;
			$result["lastDeliveryType"] = $userInfo["lastDeliveryType"]? $userInfo["lastDeliveryType"]:"delivery";
			$result['IDName']=$userInfo['IDName'];
			$result['IDNumber']=$userInfo['IDNumber'];
			$result['IDPositive'] = $userInfo['IDPositive'];
			$result['IDBack'] = $userInfo['IDBack'];
			if($result["status"]==order_status_notsubmit||$result["status"]=='paying'||$result['status']=='payingconfirm'||$result['status']=='closed'){
				if($userInfo) {
					if($userInfo['lastAddressId']){
						$addressInfo = $userAddress->where("id=".$userInfo['lastAddressId']." and deleted=0 and isAcitivity=".$result['isActivity'])->find();
						if(!$addressInfo){
							$addressInfo = $userAddress->where("uid = '$userId' and deleted=0 and isAcitivity=".$result['isActivity'])->find();			//LP修改
						}
						$result["fullName"] = $addressInfo["receiverName"];
						$result["phone"] = $addressInfo["phone"];
						$result["address"] = $addressInfo["address"];
						$result["province"] = $addressInfo['province'];
						$result["city"] = $addressInfo['city'];
						$result["country"] = $addressInfo['country'];
					}else{
						$result["fullName"] = $userInfo["fullName"];
						$result["phone"] = $userInfo["phone"];
						$result["address"] = $userInfo["address"];
					}
					if($userInfo["lastBuyStoreId"]){
						$deliveryInfo = $orderModel->alias("a")
							->join("inner join wx_".$customerId."_module_distribution_scheme b on a.distributionId=b.id")
							->join("inner join wx_".$customerId."_module_mall_delivery_type c on c.distributionId=b.id")
							->where("a.id in ($id) and c.deliveryTypeValue='pickup'")
							->field("c.categoryIds")
							->find();
						$categoryIds = explode(",",$deliveryInfo['categoryIds']);
						$storeWhere["a.id"]=array("eq",$userInfo["lastBuyStoreId"]);
						$storeWhere["a.deleted"]=array('eq',0);
						$storeWhere["a.isPickUp"]=array('eq',1);
						$result['storeInfo'] = $storeModel->alias("a")
							->join("inner join wx_store_district b on a.districtId=b.id")
							->where($storeWhere)->field("a.id,a.name,a.phone,a.address,a.contact,a.picUrl,b.districtCategoryId")
							->find();
						if(!in_array($result['storeInfo']['districtCategoryId'],$categoryIds)){
							unset($result['storeInfo']);
						}
					}
				}
			}
			if($result["deliveryType"]=="pickup"){
				$storeWhere["id"]=array("eq",$result["storeResourceId"]);
				$storeWhere["deleted"]=array('eq',0);
				$storeWhere["isPickUp"]=array('eq',1);
				$result['storeInfo'] = $storeModel->alias('a')->where($storeWhere)->field("id,name,phone,address,contact,picUrl")->find();
			}

			$price = $result["price"];
			if($result["freebuy"]) { //自由购商品
				$price=self::getOrderDetailPrice($id);
			}
			$points = $result["points"];
			$payAndLogistics = R('Mall/getPayAndLogisticsList',
					array($price, $points, $result["payType"], $result["deliveryType"], $customerId,$result['distributionId']));
			$isInvoice = R("Mall/getInvoiceSetting",array(true));
			$result['isInvoice'] = $isInvoice['isInvoice'];
			$invoice = R("Mall/getInvoice",array($userName, 0));
			$result['invoiceList'] = $invoice;
			if (count($payAndLogistics) === 0 && $result[0]['type'] != ORDER_TYPE_POINT) {
				if($noNeedJsonResult){
					Output::instance()->resultCode(code_product_pay_config);
					return;
				}else{
					return null;
				}
			}
			if ($result["status"] == order_status_notsubmit || $result["status"] == ORDER_STATUS_PAYING) {
				if ($result["price"] != NULL && $result["price"] >=0) {

					for ($i = 0; $i < count($payAndLogistics["shipping"]); $i++){
						if (array_key_exists("points", $payAndLogistics["shipping"][$i])) {
							unset($payAndLogistics["shipping"][$i]["points"]);
						}
					}
					$result = array_merge($result, $payAndLogistics);

				} else if ($result["points"] != NULL && $result["points"] != 0){
					// delete cost
					for ($i = 0; $i < count($payAndLogistics["shipping"]); $i++){
						if (array_key_exists("cost", $payAndLogistics["shipping"][$i])) {
							unset($payAndLogistics["shipping"][$i]["cost"]);
						}
					}

					$payList["shipping"] = $payAndLogistics["shipping"];
					switch ($result["payType"]) {
						case type_point_interact:
							$point["text"] = type_point_interact_display;
							$point["value"] = type_point_interact;
							break;
						case type_point_consume:
							$point["text"] = type_point_consume_display;
							$point["value"] = type_point_consume;
							break;
						default:
							if($noNeedJsonResult){
								Output::instance()->resultCode(code_product_pay_type);
								return;
							}else{
								return null;
							}
					}
					$payList["payType"] = array($point);
					//$result = array_merge($result, $payList);
				}
				$shipping=$result["shipping"];
				$result["shippingCount"] = count($shipping);
				foreach($shipping as $key=>$value){
					if($value['value']=='delivery'){
						$result["cost"]=$value["cost"];
					}
				}
                $result['deliverySta']=0;
				if($result["shippingCount"]>1){
                    if($result["lastDeliveryType"]=='delivery'){
                        $result['deliverySta']=1;//当前物流配送状态
                    }
                }else{
                    if($shipping[0]['value']=='delivery'){
                        $result['deliverySta']=1;
                    }
                }

                //查询账户余额
                if( $result['deliverySta']){
                    $price = $price-$couponMoney+$result["cost"];
                }else{
                    $price = $price-$couponMoney;
                }
                $purseWhere = [
                    'userId'    => $userId,
                    'cid'       => $result['fromCustomerId']
                ];
                $balance = $purseModel->where($purseWhere)->getField("balance");
                !$balance?$balance=0.00:"";
                $result['userBalance'] = $balance;

				/*侯佳添加于 2018-01-24*/
				$payPassword = $userModel->where("id = $userId")->getField('payPassword');//获取支付密码
				if (empty($payPassword)) {//未设置支付密码
					$payPassword = 0;
				} else {                  //已设置支付密码
					$payPassword = 1;
				}
				$result['payPassword'] = $payPassword;
				//侯佳添加2018-01-24

				//侯佳添加2018-03-14,返回用户的积分余额
				$pointBalance = $pointModel->where($purseWhere)->getField("pointBalance");
				!$pointBalance?$pointBalance=0:"";
				$result['pointBalance'] = $pointBalance;
				//侯佳添加2018-03-14
                if($balance>$price){
                    $result['canUserBalance']=$price;
                }else{
                    $result['canUserBalance'] = $balance;
                }
				if ($cardCount > 0) {
					$result['canUserBalance'] = 0;
					$result['isCard'] = 1;
				} elseif ($cardCount == 0) {
					$result['isCard'] = 0;
				}
				$bankAccount = $userModel->where(['id' => $userId])->getField('bankAccount');
				$bankAccount = json_decode($bankAccount,true);
				$bankAccount['pay'] ? $result['bankList'] = $bankAccount['pay'] : $result['bankList'] = [];
				foreach($result['payType'] as $key=>$value){
					if($value['isDefault']){
						$result['defaultPayType']=$value['value'];
						$defoaltIndex = $key;
					}
					//为了支持H5支付注释这一段对于微信支付的删除，20180419
//					if(!$result['browser']&&$result['defaultPayType']=='wxpay'){
//						array_splice($result['payType'],$defoaltIndex,1);
//						$result['defaultPayType']=$result['payType'][0]['value'];
//					}
				}
				$result['id'] = $id;
				if($noNeedJsonResult){
					self::getConfirmOrderDetailTpl($tplId, $result);
				} else{
					return $result;
				}
			} else {	// done order
				$result['id'] = $id;
				if($noNeedJsonResult){
					self::getDoneOrderDetailTpl($tplId, $result);
				} else{
					return $result;
				}
			}
		}
		Session::switchCustomer($customerId);
	}
	/**
	 * [getOrderDetailPrice 获取商品的实际总价，为自由购而设置]
	 * @param  [type] $oid [description]
	 * @return [type]      [description]
	 */
	private function getOrderDetailPrice($oid){
		$customerId = Session::$user['customerId'];
		$DetailModel = M("module_product_order_detail");
		$details=$DetailModel->where("oid in ($oid)")->select();
		Session::switchCustomer($customerId);
		$sum=0;

		foreach ($details as $key => $value) {
			$sum+=$value["price"]*$value["count"];
		}
		return $sum;
	}
	private static function getConfirmOrderDetailTpl($tplId, $result) {
        if ($tplId !== 999) {
            Output::instance()->module('product', 'product_common_order_confirm')->object($result);
        } else {
            Output::instance()->module('product', 'product_common_order_confirm_test')->object($result);
        }
		/*
		switch ($tplId) {
			case 1:
				Output::instance()->module('product', 'product_common_order_confirm')->object($result);
				break;
			case 2:
				Output::instance()->module('product', 'product_common_order_confirm')->object($result);
				//Output::instance()->module('product', 'product_single_detail_order_selected')->object($result);
				break;
			case 3:
				Output::instance()->module('product', 'product_common_order_confirm')->object($result);
				//Output::instance()->module('product', 'product_single_detail_order')->object($result);
				break;
			case 4:
				Output::instance()->module('product', 'product_common_order_confirm')->object($result);
				//Output::instance()->module('product', 'product_multi_order_confirm')->object($result);
				break;

		}
		*/
	}

	private static function getDoneOrderDetailTpl($tplId, $result) {
		switch ($tplId) {
			case 1:
			case 2:
			case 3:
				Output::instance()->module('product', 'product_common_order_detail')->object($result);
				break;
			case 4:
				Output::instance()->module('product', 'product_multi_order_detail')->object($result);
				break;
			default:
				Output::instance()->module('product', 'product_multi_order_detail')->object($result);
				break;
		}
	}

	private static function getStoreTag($sid, $type, $userName) {
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$StoreCatModel = M("store_product_category");
		$sql = $StoreCatModel->where("storeId=$sid AND type='$type'")->field("categoryId")->select(false);
		Session::switchCustomer($customerId);

		$ProductModel = M("module_product");
		$where["_string"] = "categoryId IN ($sql)";
		$where["pdt.deleted"] = 0;
		$tagList = $ProductModel->alias("pdt")->where($where)->join("RIGHT JOIN  wx_".$customerId."_module_product_tag_list list ON pdt.id=list.pid")
			->join("wx_".$customerId."_module_product_tag tag ON list.tagId = tag.id")->field("tag.*")->distinct("tag.id")->order("tag.number asc")->select();
// 		echo $ProductModel->getLastSql();

		$TagListModel = M("module_product_tag_list");
		for($i = 0; $i < count($tagList); $i++) {
			$tagId = $tagList[$i]["id"];

			$conditionTag["tag.tagId"] = $tagId;
			$conditionTag["detail.oid"] = 0;
			$conditionTag["detail.fromUserName"] = $userName;
			$conditionTag["detail.type"] = $type;
			$conditionTag["detail.storeId"] = $sid;
			$reserveCount = $TagListModel->alias("tag")->where($conditionTag)
				->join("wx_".$customerId."_module_product_order_detail detail ON detail.pid=tag.pid")->count("tag.tagId");
			$tagList[$i]["reserveCount"] = $reserveCount;
		}
		return $tagList;
	}

	public static function getProductTag($cids, $customerId, $userName, $type) {
		$ProductTagModel = M("module_product_tag");
		if ($cids != '') {
			$arrCondition = array();
			$arrCid = explode(",", $cids);
			foreach ($arrCid as $cid) {
				array_push($arrCondition, array('eq', $cid));
			}
			array_push($arrCondition, 'or');
			$where["pdt.categoryId"] = $arrCondition;
		}
		$where["tag.fromCustomerId"] = $customerId;
		$tagList = $ProductTagModel->alias("tag")->where($where)->field("tag.*")->distinct("tag.id")->order("number asc")
			->join("wx_".$customerId."_module_product_tag_list list ON tag.id = list.tagId")->join("wx_".$customerId."_module_product pdt ON list.pid = pdt.id")->select();
// 		echo $ProductTagModel->getLastSql();

		$TagListModel = M("module_product_tag_list");
		for($i = 0; $i < count($tagList); $i++) {
			$tagId = $tagList[$i]["id"];

			$conditionTag["tag.tagId"] = $tagId;
			$conditionTag["detail.oid"] = 0;
			$conditionTag["detail.fromUserName"] = $userName;
			$conditionTag["detail.type"] = $type;
			$reserveCount = $TagListModel->alias("tag")->where($conditionTag)
				->join("wx_".$customerId."_module_product_order_detail detail ON detail.pid=tag.pid")->count("tag.tagId");
// 			echo $TagListModel->getLastSql() . '</br>';
			$tagList[$i]["reserveCount"] = $reserveCount;
		}
		return $tagList;
	}


	/**
	 * 根据商品ID获取打折信息
	 * @param $pid 商品ID
	 * @return array 商品折扣、商品折扣价、商品折扣活动、商品折扣活动ID
	 */
	public static function getDiscountPrice($pid){
		$cid = Session::$user['customerId'];
		$username = Session::$user['userName'];
		$dpModule = M("discount_product");
		$where['activ.status'] = 1;
		$where['discProd.deleted'] = 0;
		$where['discProd.productId'] = $pid;
		$now = date('Y-m-d H:i:s');
		$where['activ.startTime'] = array('ELT', $now);
		$where['activ.endTime'] = array('EGT',$now);
		$discount = $dpModule
			->alias('discProd')
			->join("wx_discount disc on discProd.discountId = disc.id")
			->join("wx_activity activ on disc.activId = activ.id")
			->where($where)
			->order("activ.updateTime desc")
			->field('discProd.discountNum, discProd.discountPrice,discProd.count, discProd.personalNum, activ.id, activ.activityName,activ.startTime,activ.endTime')
			->find();
		$arr = array();
		if($discount){
			$activityId = $discount['id'];
			$activityName = $discount['activityName'];
			$discStime = $discount['startTime'];
			$discEtime = $discount['endTime'];

			if($discount['discountPrice'] ==NULL || $discount['discountNum'] == NULL){
				$arr['discNumber'] = NULL;
				$arr['discPrice'] = NULL;
				//return $arr;
			}
			$discPriceObj = json_decode($discount['discountPrice']);
			$discNumObj = json_decode($discount['discountNum']);
			$discCouObj = json_decode($discount['count']);
			$discPerObj = json_decode($discount['personalNum']);
			$MemberModel = M("member");
			$customerId = Session::$user['customerId'];
			$condition['member.fromUserName'] = array('eq',$username);
			// $level = $MemberModel->alias('member')
			// 	->join("LEFT JOIN  wx_".$customerId."_member_object object ON member.objectId = object.id")
			// 	->join("LEFT JOIN  wx_".$customerId."_member_object_level level ON member.objectLevelId = level.id")
			// 	->join("LEFT JOIN  wx_".$customerId."_member_uni_user_info info ON member.fromUserName = info.fromUserName")
			// 	->where($condition)
			// 	->field('level.`id`, level.`name`')
			// 	->find();

			// if($level){
			// 	$levelId = $level['id'];
			// 	$levelName = $level['name'];
			// }else{
			// 	$levelId = NULL;
			// 	$levelName = NULL;
			// }

			// $arr['levelId'] = $levelId;
			// $arr['levelName'] = $levelName;
			//非会员
			if(gettype($discPriceObj) != "array"){
				$arr['discNumber'] = $discNumObj;
				$arr['discPrice'] = $discPriceObj;
				$arr['count'] = $discCouObj;
				$arr['personalNum'] = $discPerObj;
				$arr['activityId'] = $activityId;
				$arr['startTime']=$discStime;
				$arr['endTime']=$discEtime;
				$arr['activityName'] = $activityName;
			}else{
				$discountNum=NULL;
				$discountPrice=NULL;
				$count=NULL;
				$personalNum=NULL;
				if($levelId != NULL){
					foreach($discNumObj as $k=>$v){
						$memberLevel = intval($levelId);
						if($v->levelId == $memberLevel) $discountNum = $v->discountNum;
					}

					foreach($discPriceObj as $k=>$v){
						$memberLevel = intval($levelId);
						if($v->levelId == $memberLevel) $discountPrice = $v->discountPrice;
					}

					foreach($discCouObj as $k=>$v){
						$memberLevel = intval($levelId);
						if($v->levelId == $memberLevel) $count = $v->count;
					}

					foreach($discPerObj as $k=>$v){
						$memberLevel = intval($levelId);
						if($v->levelId == $memberLevel) $personalNum = $v->personalNum;
					}

					$arr['discNumber'] = $discountNum;
					$arr['discPrice'] = $discountPrice;
					$arr['count'] = $count;
					$arr['personalNum'] = $personalNum;
					$arr['activityId'] = $activityId;
					$arr['startTime'] = $discStime;
					$arr['endTime'] = $discEtime;
					$arr['activityName'] = $activityName;
				}
			}

		}else{
			$arr['discNumber'] = NULL;
			$arr['discPrice'] = NULL;
			$arr['count'] = NULL;
			$arr['personalNum'] = NULL;
			$arr['activityId'] = NULL;
			$arr['startTime']=NULL;
			$arr['endTime']=NULL;
			$arr['activityName'] = NULL;
		}

		$productModel = m('module_product');
		$discountedPrice = $productModel->where("`id` = {$pid}")->getField('discountedPrice');
		if($arr['discPrice']==null) $arr['discPrice'] = $discountedPrice;

		if($arr['discPrice'] != NULL){
			$arr['discPrice'] = round($arr['discPrice'], 2);
		}

		if (is_array($arr['count'])) {
			$activcount=$arr['count'];
			$inventoryModel = M("module_product_specification");
			foreach ($activcount as $v) {
				$actwhere["pid"] = $pid;
				$actwhere["firstSpecificId"] = $v->firstid;
				$actwhere["secSpecificId"] = $v->secondid;
				$inventory = $inventoryModel->where($actwhere)->field("firstSpecificName,secSpecificName")->select();
				$key = $inventory[0]['firstSpecificName'] . '|' . $inventory[0]['secSpecificName'];
				$inv = array();
				$inv["stockCount"] = $v->count == NULL ? 0 : $v->count;
				$arr['availSku'][$key] = $inv;
			}
		}
		return $arr;
	}
	public static function realInfo($oid){
		$userName = Session::$user['userName'];
		$userId = Session::$user['userId'];
		$userInfo = get_UserInfo_by_fromUserName($userId);//LP修改
		$result['fullName'] = $userInfo['fullName'];
		$result['IDName'] = $userInfo['IDName'];
		$result['IDNumber']=$userInfo['IDNumber'];
		$result['IDPositive']=$userInfo['IDPositive'];
		$result['IDBack']=$userInfo['IDBack'];
		$result['oid']=$oid;
		$result['userName']=$userName;
		$result['mallHue']=self::getMallHue();
		Output::instance()->module("product","product_common_realInfo")->object($result);
	}
	public static function getProductList($sid, $tagIds, $cids, $userName, $type, $start = NULL, $limit = NULL,$orderBy = 'product.number desc',$screenTag=null) {
		!$orderBy?$orderBy= 'product.number desc':"";
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$periodModel = M("module_mill_period");
		$ProductModel = M("module_product_tag_list");
		$specModel = M("module_product_specification");
		if ($cids != '') {
			$arrCondition = array();
			$arrCid = explode(",", $cids);
			foreach ($arrCid as $cid) {
				array_push($arrCondition, array('eq', $cid));
			}
			array_push($arrCondition, 'or');
			$where["product.categoryId"] = $arrCondition;
		}
		$arrWhere = array();
		if($screenTag){
			$screenTag = json_decode($screenTag,true);
			$productList = $ProductModel->alias("tag");
			$asList = ["a","b","c"];
			$where["product.isGroup"] = 0;
			$where["product.deleted"] = 0;
			$where["product.isRemoved"] = 0;
			$where["product.fromCustomerId"] = $customerId;
			foreach($screenTag as $key=>$value){
				$productList = $productList->join("inner join wx_module_product_tag_list ".$asList[$key]." ON ".$asList[$key].".pid=tag.pid");
				$value = json_decode($value,true);
				$tags = $value['tags'];
				$tags = explode(",", $tags);
				$arrTag = array();
				if($key>0){
					foreach($tags as $t=>$tag){
						array_push($arrTag, $asList[$key-1].".tagId=$tag");
					}
				}else{
					foreach($tags as $t=>$tag){
						array_push($arrTag, "tag.tagId=$tag");
					}
				}
				$arrTag = implode(" or ",$arrTag);
				array_push($arrWhere, "($arrTag)");
			}
			$arrWhere = implode(" and ",$arrWhere);
			$where["_complex"] =$arrWhere;
			$productList = $productList->join("wx_module_product product ON tag.pid=product.id")
				->join("wx_module_product_specification spe on product.id=spe.pid")
				->order($orderBy)
				->where($where);
			if (isset($start)&&isset($limit)) {
				$productList = $productList->limit("$start, $limit");
			}
			$productList = $productList->field("product.*,MIN(spe.discountedPrice) as minDisPrice,MAX(spe.discountedPrice) as maxDisPrice,
				MIN(spe.miPrice) as minMiPrice,MAX(spe.miPrice) as maxMiPrice,MAX(spe.fixedPrice) as maxFixedPrice,MIN(spe.fixedPrice) as minFixedPrice,MAX(spe.seckillPrice) as maxSeckillPrice,MIN(spe.seckillPrice) as minSeckillPrice")
				->group("product.id");
			$productList = $productList->select();
			$proTotal = $ProductModel->alias("tag");
			foreach($screenTag as $key=>$value) {
				$proTotal = $proTotal->join("inner join wx_module_product_tag_list " . $asList[$key] . " ON " . $asList[$key] . ".pid=tag.pid");
			}
			$proTotal = $proTotal->join("wx_module_product product ON tag.pid=product.id")
				->join("wx_module_product_specification spe on product.id=spe.pid")
				->order($orderBy)
				->where($where);
			$proTotal = $proTotal->field("product.id")->group("product.id")->select();
			$total = count($proTotal);
		}else{
			$arrTag = explode(",", $tagIds);
			if (count($arrTag) > 0) {
				foreach ($arrTag as $key=>$tag) {
					array_push($arrWhere, array('eq', $tag));
				}
				array_push($arrWhere, 'or');
				$where["tag.tagId"] = $arrWhere;
			} else {
				$where["tag.tagId"] = $tagIds;
			}
			$where["product.isGroup"] = 0;
			$where["product.deleted"] = 0;
			$where["product.isRemoved"] = 0;
			$where["product.fromCustomerId"] = $customerId;
			if (!isset($start) || !isset($limit)) {
				$productList = $ProductModel->alias("tag")
					->where($where)
					->join("wx_module_product product ON tag.pid=product.id")
					->join("wx_module_product_specification spe on product.id=spe.pid")
					->order($orderBy)
					->field("product.*,MIN(spe.discountedPrice) as minDisPrice,MAX(spe.discountedPrice) as maxDisPrice,
				MIN(spe.miPrice) as minMiPrice,MAX(spe.miPrice) as maxMiPrice,MAX(spe.fixedPrice) as maxFixedPrice,MIN(spe.fixedPrice) as minFixedPrice,MAX(spe.seckillPrice) as maxSeckillPrice,MIN(spe.seckillPrice) as minSeckillPrice")
					->group("product.id")
					->select();
			} else {
				$where["m.module"] ='product';
				$productList = $ProductModel
					->alias("tag")
					->join("wx_module_product product ON tag.pid=product.id")
					->join("wx_mishare m on m.moduleId=product.id")
					->join("wx_module_product_specification spe on product.id=spe.pid")
					->where($where)
					->order($orderBy)
					->field("product.*,m.id as sId,MIN(spe.discountedPrice) as minDisPrice,MAX(spe.discountedPrice) as maxDisPrice,
				MIN(spe.miPrice) as minMiPrice,MAX(spe.miPrice) as maxMiPrice,MAX(spe.fixedPrice) as maxFixedPrice,MIN(spe.fixedPrice) as minFixedPrice,MAX(spe.seckillPrice) as maxSeckillPrice,MIN(spe.seckillPrice) as minSeckillPrice")
					->limit("$start, $limit")
					->group("product.id")
					->select();
				//Log::write('jie------t13t14-getMaterial-'.($t14-$t13));
			}
			$total = $ProductModel
				->alias("tag")
				->join("wx_module_product product ON tag.pid=product.id")
				->join("wx_mishare m on m.moduleId=product.id")
				->where($where)
				->field("product.id")
				->group("product.id")->select();
			$total = count($total);
		}
		foreach($productList as $key => $value){
			if($value['isChainPro']){
				//主键查询
				$supProductInfo = $ProductModel->table("wx_module_product")->where("id=".$value['supplyProId'])->find();
				$productList[$key]['inventoryCount']=$supProductInfo['inventoryCount'];
				$productList[$key]['inventory']=$supProductInfo['inventory'];
			}
			$productList[$key]['picUrl1']=json_decode($value['picUrl1'],true);
			$json = json_decode($value["json"],true);
			$jsonName = array_keys($json);
			foreach($jsonName as $k=>$val){
				$productList[$key][$val]=$json[$val];
				$value[$val]=$json[$val];
			}
			if($value["playType"]=="4"){
				$productList[$key]['inventory'] = 1;
				$seckillStartTime = strtotime($json["seckillStartTime"]);
				$seckillEndtime = strtotime($json["seckillEndTime"]);
				$newTime = time();
				$productList[$key]["seckillIsEnd"]=0;
				if($newTime>=$seckillStartTime){
					$productList[$key]["seckillIsStart"]=1;
				}else{
					$productList[$key]["seckillIsStart"]=0;
				}
				if($newTime>$seckillEndtime){
					$productList[$key]["seckillIsEnd"]=1;
				}
				if($value['supportSpecification']){
					$specList = $specModel->where("pid=".$value['id'])->select();
					$temp = 0;
					if($json['seckillSpecPreSalceCount']) {
						$json['seckillSpecPreSalceCount'] = json_decode($json['seckillSpecPreSalceCount'], true);
						foreach ($specList as $s => $spec) {
							foreach ($json['seckillSpecPreSalceCount'] as $c => $count) {
								if ($spec['firstSpecificId'] == $count['firstid'] && $spec['secSpecificId'] == $count['secondid']) {
									$count['count'] ? $temp += $count['count'] : "";
								}
							}
						}
					}
					$productList[$key]['seckillInventoryCount']-=$temp;
//					!$temp?$productList[$key]["seckillIsEnd"]=1:'';
				}else{
					$json['seckillPreSalceCount']?$productList[$key]['seckillInventoryCount']-=$json['seckillPreSalceCount']:"";
//					$productList[$key]['seckillInventoryCount']<=0?$productList[$key]["seckillIsEnd"]=1:'';
				}
				$productList[$key]["seckillIsStart"]?$productList[$key]['inventoryCount'] = $productList[$key]['seckillInventoryCount']:"";
				if($productList[$key]["seckillIsEnd"]!=1&&$productList[$key]["seckillIsStart"]==1){
					if($productList[$key]['supportSpecification']==1){
						$productList[$key]['minDisPrice'] = $productList[$key]['minSeckillPrice'];
						$productList[$key]['maxDisPrice'] = $productList[$key]['maxSeckillPrice'];
					}else{
						$productList[$key]['discountedPrice'] = $productList[$key]['seckillPrice'];
					}
				}
				$productList[$key]['inventoryCount'] = $productList[$key]['seckillInventoryCount'];
				$productList[$key]["nowTime"] = date("Y-m-d H:i:s");
			}else if($value["playType"]=="3"){
				$periodInfo = $periodModel->where("pid=".$value["id"])->field("beenSold,periodState")->order("id desc")->find();
				if(!$periodInfo["beenSold"]){
					$periodInfo["beenSold"]=0;
				}
				$productList[$key]["beenSold"] = $value["totalCopies"]-$periodInfo["beenSold"];
				$productList[$key]["periodState"] = $periodInfo["periodState"];
				$productList[$key]["barProgress"] = floor($periodInfo["beenSold"]/$value["totalCopies"]*100)."%";
			}else if($value["playType"]=="6") {
				$value['supportSum']?"":$value['supportSum']=0;
				$productList[$key]['day']=ceil((strtotime($value['crowEndtime'])-time())/(24*60*60));
				$productList[$key]["barProgress"] = ceil($value["supportSum"]/$value["crowTarget"]*100)."%";
			}
			$value["picTag"]?$productList[$key]["picTag"] = explode(",",$value["picTag"]):'';
			$value["priceTag"]?$productList[$key]["priceTag"] = explode(",",$value["priceTag"]):'';
			unset($productList[$key]["json"]);
		}

		if ($sid != '') {
			$Detail = M("module_product_order_detail");
			$conditionDetail["storeId"] = $sid;
			$conditionDetail["oid"] = 0;
			$conditionDetail["fromUserName"] = $userName;
			$conditionDetail["type"] = $type;
			$detailList = $Detail->where($conditionDetail)->select();
			for ($i = 0; $i < count($productList); $i++) {
				$pid = $productList[$i]["id"];
				$count = 0;
				for ($j = 0; $j < count($detailList); $j++) {
					if ($detailList[$j]["pid"] == $pid) {
						$count = $detailList[$j]["count"];
						// remove it
						array_splice($detailList, $j, 1);
						break;
					}
				}
				$productList[$i]["count"] = $count;
			}
		}
		// foreach($productList as $k => $v){
		// 	$discount = self::getDiscountPrice($v['id']);
		// 	$productList[$k]['discountedPrice']=$discount['discPrice'];
		// 	$productList[$k]['startTime']=$discount['startTime'];
		// 	$productList[$k]['endTime']=$discount['endTime'];
		// }
		$result["total"] = $total;
		$result["productList"] = $productList;
		Session::switchCustomer($customerId);
		return $result;
	}

	public static function getTemplateById($tplid){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$WebPageModel = M("pb_template");
		$where['id'] = array('eq',$tplid);
		$res = $WebPageModel -> where($where)->find();
		Session::switchCustomer($customerId);
		return $res;
	}

	/**
	 * 获取商品信息
	 * 优化加缓存,键值以商品id拼接对应信息
	 * @param $param /手机端参数
	 */
    public static function getProduct($param) {
		$customerId = Session::$user['customerId'];
		$userName = Session::$user['userName'];
		$userId = Session::$user['userId'];
		$mallModel=M("module_mall_store");
		Session::switchCustomer(0);
		$ProductModel = M("module_product");
		$specModel = M("module_product_specification");
		$periodModel = M("module_mill_period");
        $parModel=M("module_mill_par");
        $numberModel=M("module_mill_number");
		$FavModel = M("module_product_favorite");
		$tagList = M("module_product_tag_list");
        $quan_user_tab = M("quan_user");
$mimall_user_tab=M('mimall_user');
		$pointScheme_tab = M('module_point_scheme');
        $posterModel = m('poster');
		Session::switchCustomer($customerId);
		$distribution = M("module_distribution_scheme");
		$allUserModel=M("user");
		$userModule = M("user_weixin_info");
		$MallStoreModel = m('module_mall_store');
		$pid=$param->id;
		$rootId=$param->rootid;
		$perId=$param->periodId;
		$fromOpenId = $param->fromOpenId;
		$fromUserName = $param->fromUserName;
		if(!$fromOpenId){
			$fromOpenId=$userName;
		}
		//获取店铺信息
		$redis = new RedisAPI();
		$mallResult = $redis->get('cid'.$customerId.'mallInfo');
		if($mallResult){
			$mallResult = unserialize($mallResult);
		}else{
			$mallResult=$mallModel->find();
			$redis->set('cid'.$customerId.'mallInfo', serialize($mallResult), 12*60*60);
		}

		$where["pdt.id"] = $pid;
		$where["pdt.isRemoved"] = 0;
		$where["pdt.deleted"] = 0;
        $where["b.module"] ="product";

		$proKey = $pid;
		$productInfo = $redis->get('cid'.$customerId.'pid'.$proKey.'productInfo');
		if($productInfo){
			$productInfo = unserialize($productInfo);
		}else{
			$productInfo = $ProductModel->where("id=".$pid)->field("isRemoved")->find();
			$redis->set('cid'.$customerId.'pid'.$proKey.'productInfo', serialize($productInfo), 12*60*60);
		}
		//判断商品是否下架
			if($productInfo["isRemoved"]==1){
				Output::instance()->resultCode(1,"噢噢，活动结束鸟，产品已下架，欲知后事如何，请紧密关注！");
				return;
			}
		/* 此处暂时先注释掉, 1112
		 * $groupId = $tagList->alias("a")
			->join("inner join wx_".$customerId."_user_tag_group b on a.tagId=b.tagId")
			->where("a.pid=$pid and b.type='product'")->order("b.createTime desc")->getField("b.groupId");

		if($groupId){
			$groupList = $allUserModel->where("userName='$userName'")->getField("groupId");
			$groupList = explode(",",$groupList);
			$flag = true;
			$openids[] = $userName;
			foreach($groupList as $key=>$value){
				if($value==$groupId){
					$flag = false;
				}else{
					WeixinApi::deletedUsersTag($openids,$value);
				}
			}
			if($flag){
				WeixinApi::setUsersTag($openids,$groupId);
			}
			if(count($groupList)>1||$groupList[0]!=$groupId){
				$allUserModel->where("userName='$userName'")->setField("groupId",$groupId);
			}
		}*/
		//获取产品信息
		/*$value = $redis->get('cid'.$customerId.'pid'.$proKey);
		if($value){
			$result = unserialize($value);
		}else{*/
			$result = $ProductModel->alias("pdt")
				->join("inner join wx_mishare b on pdt.id=b.moduleId")
				->join("inner join wx_mishare_material c on b.id=c.sId")
				->join("wx_module_product_specification spe on pdt.id=spe.pid")
				->join("wx_module_mall_share_store d on pdt.microId=d.mallId and d.customerId=$customerId")//货架分享表
				->where($where)
				->field("pdt.*,b.id as sId,c.shareImg,c.title,c.description as cDescription,d.mallShareTitle,d.mallShareDesc,d.mallShareLogo,
				MIN(spe.discountedPrice) as minDisPrice,MAX(spe.discountedPrice) as maxDisPrice,MIN(spe.saleCut) as minSaleCut,MAX(spe.saleCut) as maxSaleCut,
				MIN(spe.miPrice) as minMiPrice,MAX(spe.miPrice) as maxMiPrice,MAX(spe.fixedPrice) as maxFixedPrice,MIN(spe.fixedPrice) as minFixedPrice,
				MAX(spe.seckillPrice) as maxSeckillPrice,MIN(spe.seckillPrice) as minSeckillPrice,MAX(spe.seckillSalce) as maxSeckillSalce,MIN(spe.seckillSalce) as minSeckillSalce")
				->find();
			//$redis->set('cid'.$customerId.'pid'.$proKey, serialize($result), 24*60*60);
		//}
		if (!$result['id']) { //判断商品是否存在
			Output::instance()->resultCode(code_product_not_exist);
			return;
		}

		//处理获取分享需要数据
		$shareArr = [];
		$shareArr['id'] = $result['id'];
		$shareArr['fromCustomerId'] = $result['fromCustomerId'];
		$shareArr['tplId'] = $result['tplId'];
		$shareArr['name'] = $result['name'];
		$shareArr['title'] = $result['title'];
		$shareArr['recommend'] = $result['recommend'];
		$shareArr['description'] = $result['description'];
		$result['description'] = $result['cDescription'];

		$resMallHue = $redis->get('cid'.$customerId.'pid'.$proKey.'mallHue');
		if(is_numeric($resMallHue)){
			$mallHue = $resMallHue;
		}else{
			$mallHue = $MallStoreModel->getField("mallHue");
			$redis->set('cid'.$customerId.'pid'.$proKey.'mallHue', $mallHue, 24*60*60);
		}
		$mallHueArr = [];
		if($mallHue == 1){
			$mallHueArr['mallHue'] = $mallHue;
			$mallHueArr['mainColor'] = '#3c8bce';
			$mallHueArr['secondaryColor'] = '';
			$mallHueArr['fontColor'] = '#ff0000';
			$mallHueArr['proDetailMainColor'] = '#FE0300';
		}
		$result['mallHue']=$mallHueArr; //获取商城基本色调
		if(!$result['distributionId']){
			$distriWhere['isDefault'] = array('eq',1);
			$distriWhere['deleted'] = array('eq',0);
			$distributionInfo = $distribution->where($distriWhere)->field('id')->find();
			$result['distributionId'] = $distributionInfo['id'];
		}
		//判断是否享有密友价
		$isMiYou = $redis->get('cid'.$customerId.'userId'.$userId.'isMiYou');
		if(is_numeric($isMiYou)){
			$isMY = $isMiYou;
		}else{
			$isMY = self::isEnjoyMiPrice($param);
			$isMY?$isMY=1:$isMY=0;
			if($userId){
				$redis->set('cid'.$customerId.'userId'.$userId.'isMiYou', $isMY, 60*60);
			}
		}
		if($isMY){
			$result['isEnjoyMiPrice']=1;
		}else{
			$result['isEnjoyMiPrice']=0;
		}

		$json = json_decode($result["json"],true);
		$jsonName = array_keys($json);
		foreach($jsonName as $key=>$value){
			$result[$value]=$json[$value];
		}
		if($result['playType']==6){
			!$result['supportPerson']?$result['supportPerson']=0:"";
			!$result['supportSum']?$result['supportSum']=0:"";
			!$result['supportPerson']?$result['supportPerson']=0:"";
			$result['progress'] = round($result['supportSum']/$result['crowTarget']*100);
			$nowTime = time();
			if(strtotime($result['crowStarttime'])>$nowTime){
				$result['day']=ceil((strtotime($result['crowStarttime'])-$nowTime)/(24*60*60));
			}else if(strtotime($result['crowEndtime'])<$nowTime){
				$result['isEnd']=1;
				$result['day']=ceil(($nowTime-strtotime($result['crowEndtime']))/(24*60*60));
			}else{
				$result['isStart']=1;
				$result['day']=ceil((strtotime($result['crowEndtime'])-$nowTime)/(24*60*60));
			}
		}

		if($result["activityinfo"]){
			$activityinfo = json_decode($result["activityinfo"],true);
			$activityinfoName = array_keys($activityinfo);
			foreach($activityinfoName as $key=>$value){
				$result[$value]=$activityinfo[$value];
			}
		}
		if($result['customized']){
			foreach($result['customized'] as $key=>$value){
				if($value['type']==2){
					$result['customized'][$key]['description']=explode(",",$value['description']);
				}
			}
		}
		if($result["playType"]==4){
			$result['inventory'] = 1;
			$seckillStartTime = strtotime($result["seckillStartTime"]);
			$seckillEndtime = strtotime($result["seckillEndTime"]);
			$newTime = time();
			$result["seckillIsEnd"]=0;
			if($result['supportSpecification']){
				$specList = $specModel->where("pid=$pid")->select();
				if($json['seckillSpecPreSalceCount']){
					$temp = 0;
					$json['seckillSpecPreSalceCount'] = json_decode($json['seckillSpecPreSalceCount'],true);
					foreach($specList as $s=>$spec){
						foreach($json['seckillSpecPreSalceCount'] as $count){
							if($spec['firstSpecificId']==$count['firstid']&&$spec['secSpecificId']==$count['secondid']){
								$count['count']?$temp+=$count['count']:"";;
							}
						}
					}
					$result['seckillInventoryCount']-=$temp;
				}
			}else{
				if($json['seckillPreSalceCount']&&$result['seckillInventoryCount']-$json['seckillPreSalceCount']<=0){
					$result['seckillInventoryCount']-=$json['seckillPreSalceCount'];
				}
			}
			if($newTime>=$seckillStartTime){
				$result["seckillIsStart"]=1;
			}else{
				$result["seckillIsStart"]=0;
			}
			if($newTime>$seckillEndtime){
				$result["seckillIsEnd"]=1;
			}
			if($json['seckillPreEndTime']) {
				$seckillEndtime =$seckillStartTime+ $json['seckillPreEndTime'];
				if($newTime>$seckillEndtime){
					$result['seckillInventoryCount'] = 0;
				}
			}
			$result["seckillIsStart"]&&!$result["seckillIsEnd"]?$result['inventoryCount'] = $result['seckillInventoryCount']:"";
			$result["nowTime"] = date("Y-m-d H:i:s");
			unset($result["json"]);
		}
		if($result["picTag"]){ //商品主图标签
			$result["picTag"] = explode(",",$result["picTag"]);
		}
		if($result["priceTag"]){ //商品价格后边的标签
			$result["priceTag"] = explode(",",$result["priceTag"]);
		}
        $arr["newperiod"]=null;   //最新一期信息
        $arr["user_me"]=null;    //当前用户的购买数据
        $arr["winning"]=null;    //中奖用户数据
		if($result['playType']=="3"){  //判断夺宝商品
            //找到此商品最新一期的开启情况
			$where2['a.pid'] = $pid;
			if($perId){
				$where2['a.id']=$perId;
			}
			$arr["newperiod"] = $periodModel->alias("a")
					->where($where2)
                    ->field("a.id,a.beenSold,a.surplus,a.periodState,a.wNumber,a.updataTime,a.createTime,a.perNumber")->order('id desc')->find();
			$periodId=$arr["newperiod"]["id"];
            if($arr["newperiod"]['periodState']=="1"){
                $periodId=$arr["newperiod"]["id"];
            }
            else if($arr["newperiod"]['periodState']=="3"){
                $periodId=$arr["newperiod"]["id"];
                //已经开奖,获取中奖用户
				$arr["winning"]["list"] = $parModel->alias("a")
							->join("left join wx_".$customerId."_user_weixin_info c on a.openId = c.openid")
							->where("a.perId=$periodId and (a.parState = 2 or a.parState = 3)")
							->field("a.perId,a.parState,a.openId,a.ip,a.city,c.nickname,c.headimgurl")
							->distinct(true)
							->group("a.openId")
							->order("a.parState")
							->select();
				foreach($arr["winning"]["list"] as $key=>$value){
					//中推荐奖用户
					if($value["parState"]=="2"){
						$winnerOpenId = $value["openId"];
					}
				}
				$list = $parModel->alias(a)
					->join("inner join wx_module_product_order b on a.oid = b.id")
					->where("a.perId=$periodId and a.openId='$winnerOpenId' and (b.status = 'partake' or b.status = '".order_status_ok."' or b.status = '".order_status_delivered."' or b.status = '".order_status_refund."' or b.status = '".ORDER_STATUS_REFUNDEDPART."')")->field("a.count")->select();
				$count=0;
				foreach($list as $key=>$value){
					$count+=$value["count"];
				}
				$arr["winning"]["count"]=$count;
            }
            //其它情况新开一期
            else if(!$perId){
                //新开
				if($result['inventory']=="0"||($result['inventory']=="1"&&$result['inventoryCount']>0)){
					$perId = self::startNewPeriod($pid,$result["totalCopies"]);
					$arr["newperiod"] =$periodModel->alias("a")
						->where("a.id=".$perId)
						->field("a.id,a.beenSold,a.surplus,a.periodState,a.wNumber,a.updataTime,a.createTime,a.perNumber")->find();
					$periodId=$arr["newperiod"]["id"];
				}
            }
			$arr["newperiod"]["fromOpenId"] = $fromOpenId;
            /*查看当前用户这一期参与数据*/
			$arr["user_me"]["list"] = $numberModel->alias("a")
				->where("a.perId=$periodId and a.openId='".$userName."'")
				->field("a.number")
				->select();
			$arr["user_me"]["joinCount"]= count($arr["user_me"]["list"]);
			$userInfo = $userModule->where("openid='".$userName."'")->field("headimgurl")->find();
			$arr["user_me"]["headimgurl"] = $userInfo["headimgurl"];
			$arr["user_me"]["count"] = count($arr["user_me"]["list"]);
            $result["millData"]=$arr;
		}
//        $result["webPageContent"]=htmlentities($result["webPageContent"]);
		$tplId=$result["tplId"];
		$result["freeBuyMoney"]=explode(',', $result["freeBuyMoney"]);
		$result["picUrl1"]=json_decode($result["picUrl1"]);

		Log::write('11111-user:'.$userId.'|moduleId:'.$result['id']);
		if(!$result['pointSchemeId']){
			$result['pointSchemeId'] = $pointScheme_tab->where(['cid' => $customerId, 'default' => 1, 'status' => 1, 'deleted' => 0])->getField('id');
		}
		/*处理积分奖励*/
		if($result['pointSchemeId'] && $fromUserName){
			R('Point/addVisitPoint', [$result['pointSchemeId'],$fromUserName,$userId,'product',$result['id'],$result['name'],$customerId]);
		}

		//添加访问记录
		$visitParam=new StdClass();
//		$Guid = new Guid();
//		$guid = $Guid->toString();
//		$visitParam->guid=$guid;
//		$visitParam->fromGuid=$param->fromGuid;
		$visitParam->sId=$result["sId"];
		$visitParam->miUId=$param->miUId;;								//密友id
		$visitParam->saleSourceUid=$param->saleSourceUid;			//销售源id
		$visitParam->visitId= $param->visitId;							//上一次浏览id
		$visitParam->qId=$param->qId;
		$visitParam->fromPage="product_detail";
		$visitParam->lastShareUId= $param->lastShareUId;
		//待进一步优化
		$visitId = Module::callModule("quan", Session::$user,"addVisit", $visitParam);
		$param->visitId=$visitId;
		$detail = self::getObjectDetail($param, $shareArr);
		$result["visitId"]=$visitId;    //返回浏览记录id

//		$result["guid"]=$guid;
		//$arr = self::getDiscountPrice($result['id']);
		// $result['discountedPrice'] = $arr['discPrice']; //折扣价
		// $result['startTime'] = $arr['startTime'];
		// $result['endTime'] = $arr['endTime'];
		// if (isset($arr['count'])&& $arr['count']<=$result['inventoryCount'] && $arr['count'] !== 0) {
		// 	$result['inventoryCount'] = $arr['count']; //折扣价
		// }
		// $result['personalNum']=$arr['personalNum'];

		/*积分表, 此处没有作用, 暂时注释*/
		//set_point_by_point_type(module_handle_browseProduct, $userName, false,$result['name']);

		//判断是否有访问标签
		if ($result["accessTag"] != NULL) {
			if (!isset($userName)) {
				$userName = NULL;
			}
		}

		if ($userName == '') {
			$result["showBtn"] = 0;
		} else {
			$result["showBtn"] = 1;
			$condition["pid"] = $pid;
			$condition["fromCustomerId"] = $customerId;
			$condition["fromUserName"] = $userName;
			$fav = $FavModel->where($condition)->find();
			if (!$fav) {
				$result["favorite"] = 0;
			} else {
				$result["favorite"] = 1;
			}
		}

		$time=time();
		if($result["teambuy"]=="1" && $result["teamStartTime"]) {
			if($time >= strtotime($result["teamStartTime"])){
				$result["isStart"]=1;
			} else {
				$result["isStart"]="0";
			}
			if($time >= strtotime($result["teamEndTime"])){
				$result["isEnd"]=1;
			} else {
				$result["isEnd"]="0";
			}
//			$tuanParam = new stdClass();
//			$tuanParam->pid = $pid;
//			$tuanParam->unPhone = 1;
//			$teamCount = Module::callModule("tuan", NULL,"getTeamOrderList", $tuanParam);
//			if($teamCount>0){
//				$result["hasList"]=1;
//			}else{
//				$result["hasList"]=0;
//			}
		}
		if($result['isChainPro']){ //供应链商品
			$supplyProInfo = $ProductModel->where("id=".$result['supplyProId'])->find();
			$result['inventoryCount']=$supplyProInfo['inventoryCount'];
			$result['inventory']=$supplyProInfo['inventory'];
		}
		// 获取规格,暂未优化
		//$t3 = microtime(true);
		if ($result["supportSpecification"] == 1) {
			$arrFirstSpec = $redis->get('cid'.$customerId.'pid'.$proKey.'firstSpec');
			if($arrFirstSpec){
				$arrFirstSpec = unserialize($arrFirstSpec);
			}else{
				$arrFirstSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
					->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
					->order("sepc.id")
					->getField("specificationName", true);
				$redis->set('cid'.$customerId.'pid'.$proKey.'firstSpec', serialize($arrFirstSpec), 12*60*60);
			}
			//sql1
			$arrFirstSpecurl = $redis->get('cid'.$customerId.'pid'.$proKey.'firstSpecUrl');
			if($arrFirstSpecurl){
				$arrFirstSpecurl = unserialize($arrFirstSpecurl);
			}else{
				$arrFirstSpecurl = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
					->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
					->order("sepc.id")
					->getField("specificationUrl", true);
				$redis->set('cid'.$customerId.'pid'.$proKey.'firstSpecUrl', serialize($arrFirstSpecurl), 12*60*60);
			}
			//sql2
			if ($arrFirstSpec) {
				$sizeUnit = $redis->get('cid'.$customerId.'pid'.$proKey.'sizeUnit');
				if($sizeUnit){
					$sizeUnit = unserialize($sizeUnit);
				}else{
					$sizeUnit =  $specModel->alias("sepc")->where("sepc.pid=$pid")->distinct("specificationName")
						->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
						->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
						->getField("groupName");
					$redis->set('cid'.$customerId.'pid'.$proKey.'sizeUnit', serialize($sizeUnit), 12*60*60);
				}

				$result["sizeUnit"] = $sizeUnit;
				//sql3
			}
			$result["size"] = json_encode($arrFirstSpec);
			if ($arrFirstSpecurl) {
				$result["sizeurl"] = json_encode($arrFirstSpecurl);
			}
			$arrSecSpec = $redis->get('cid'.$customerId.'pid'.$proKey.'arrSecSpec');
			if($arrSecSpec){
				$arrSecSpec = unserialize($arrSecSpec);
			}else{
				$arrSecSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
					->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
					->getField("specificationName", true);
				$redis->set('cid'.$customerId.'pid'.$proKey.'arrSecSpec', serialize($arrSecSpec), 12*60*60);
			}
			//sql4
			$arrSecSpecurl = $redis->get('cid'.$customerId.'pid'.$proKey.'arrSecSpecurl');
			if($arrSecSpecurl){
				$arrSecSpecurl = unserialize($arrSecSpecurl);
			}else{
				$arrSecSpecurl = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
					->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
					->getField("specificationUrl", true);
				$redis->set('cid'.$customerId.'pid'.$proKey.'arrSecSpecurl', serialize($arrSecSpecurl), 12*60*60);
			}
			//sql5
			if ($arrSecSpec) {
				$colorUnit = $redis->get('cid'.$customerId.'pid'.$proKey.'colorUnit');
				if($colorUnit){
					$colorUnit = unserialize($colorUnit);
				}else{
					 $colorUnit = $specModel->alias("sepc")->where("sepc.pid=$pid")->distinct("specificationName")
						->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
						->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
						->getField("groupName");
					$redis->set('cid'.$customerId.'pid'.$proKey.'colorUnit', serialize($colorUnit), 12*60*60);
				}
				$result["colorUnit"] = $colorUnit;
				//sql6
			}
			$result["color"] = json_encode($arrSecSpec);
			if ($arrSecSpecurl) {
				$result["colorurl"] = json_encode($arrSecSpecurl);
			}

			if ($result["supportSpecification"] == 1) {
				if (isset($arr['availSku'])) {
					$availSku=$arr['availSku'];
				}else{
					$availSku = self::getProductInventory(array(
						"pid"=>$pid,
						"arrFirstSpec"=>$arrFirstSpec,
						"arrSecSpec"=>$arrSecSpec
					));
				}

				if($result['playType']==4&&$result['seckillIsStart']&&!$result['seckillIsEnd']){
					foreach($availSku as $key=>$item){
						$availSku[$key]['inventoryCount'] = $item['seckillInventoryCount'];
						$availSku[$key]['discountedPrice'] = $item['seckillPrice'];
					}
					if($json['seckillSpecPreSalceCount']) {
						foreach ($json['seckillSpecPreSalceCount'] as $c => $count) {
							if($count['count']&&$availSku[$count['firstname']."|".$count['secondname']]['inventoryCount'] - $count['count']<=0){
								$availSku[$count['firstname']."|".$count['secondname']]['inventoryCount'] -= $count['count'];
							}
						}
					}
				}
				$result["availSku"] = json_encode($availSku);
			}
		}
		/*$t4 = microtime(true);
		Log::write('jie-----t3t4'.($t4-$t3));*/
		if (!isset($result["size"])) {
			$result["size"] = json_encode(null);
		}
		if (!isset($result["color"])) {
			$result["color"] = json_encode(null);
		}
		if (!isset($result["availSku"])) {
			$result["availSku"] = json_encode(null);
		}
		if (isset($rootId)) {
			$materialObjNav = self::getMaterialObj($rootId);
			if ($materialObjNav != NULL) {
				$nav = self::getNav($materialObjNav, $customerId, $userName, $rootId);
				$result["header"] = $nav["header"];
				$result["footer"] = $nav["footer"];
				$result["headerTpl"] = $nav["headerTpl"];
				$result["footerTpl"] = $nav["footerTpl"];
			}
		}
		if(!empty($result['accessTag']) && !empty($userName)){
			setAccessTags($result['accessTag'],$userName,module_handle_product, $pid);
		}

		$tpl = $redis->get('cid'.$customerId.'pid'.$proKey.'template');
		$tpl = unserialize($tpl);
		if(!$tpl){
			$tpl=self::getTemplateById($tplId);
			if(!$tpl){
				//当没有设置tpl时设置假数据,避免每次查询
				$tpl = 'noset';
			}
			$redis->set('cid'.$customerId.'pid'.$proKey.'template', serialize($tpl), 12*60*60);
		}
		if($tpl == 'noset'){
			$tpl = '';
		}
		//Log::write('jie----t17t18getTemplateById'.($t18-$t17));
		if($tpl) {
			$tplHtmlName=$tpl["htmlname"];
		}
		if(!$tplHtmlName) {
			$tplHtmlName="product_common_new_detail";
		}
		$result["mall"]=$mallResult;
		$presult = $redis->get('cid'.$customerId.'userId'.$userId.'userInfo');
		if($presult){
			$presult = unserialize($presult);
		}else{
			$presult=$allUserModel
				->alias("a")
				->field("a.status,c.nickName,c.headImgUrl,a.phone,a.fullName,a.email,a.city,a.province,
				a.birthday,a.address")
				->join("inner join wx_".$customerId."_user_weixin_info c on c.openid=a.userName")
				->where("a.userName='".$userName."'")
				->find();
			if($userId){
				$redis->set('cid'.$customerId.'userId'.$userId.'userInfo', serialize($presult), 60*60);
			}
		}
		/*注册是带入历史信息jie*/
		$result['userInfo']= $presult;
		$result["subscribe"]=0;
		if(!$mallResult['wechaturl']||$presult["status"]=='subscribe'||$presult["status"]=='scansubscribe'||!isMicroMessengerUserAgent()){
			$result["subscribe"]=1;
		}

		$quanInfo = self::isPartner();
		//Log::write('jie----t21t22'.($t22-$t21));
		if($result['playType']==4&&$result['seckillIsStart']==1&&$result['seckillIsEnd']!=1&&$result['supportSpecification']==1){
			$result["isMiUserCut"] = round($result['minSeckillSalce']*$quanInfo['miAward'],2)."~".round($result['maxSeckillSalce']*$quanInfo['miAward'],2);
		}else if($result['playType']==4&&$result['seckillIsStart']==1&&$result['seckillIsEnd']!=1){
			$result["isMiUserCut"] = round($result['seckillSalce']*$quanInfo['miAward'],2);
		} else if($result['supportSpecification']==1&&$result['minSaleCut']!=$result['maxSaleCut']){
			$result["isMiUserCut"] = round($result['minSaleCut']*$quanInfo['miAward'],2)."~".round($result['maxSaleCut']*$quanInfo['miAward'],2);
		}else if($result['supportSpecification']==1){
			$result["isMiUserCut"] = round($result['minSaleCut']*$quanInfo['miAward'],2);
		}else{
			$result["isMiUserCut"] = round($result['saleCut']*$quanInfo['miAward'],2);
		}
		$result['quanInfo']= $quanInfo;
		$result["customerId"] = $customerId;
		$result["nickName"]=$presult["nickName"];
		$result["headImgUrl"]=$presult["headImgUrl"];
        if(!$param->miUId && !empty($quanInfo)){
            $param->miUId = $userId;
        }
if(!$param->saleSourceUid){
    $saleSource = $mimall_user_tab->where("uId=$userId and cId=$customerId")->getField("saleSource");
    $result['saleSourceUid'] = $saleSource;
}else{
    $result['saleSourceUid'] = $param->saleSourceUid;
}
		$result["miUId"]=$param->miUId;
		if(!$param->qId){
			$param->qId = $quanInfo['qId'];
		}
		//判断是否展示海报
        $posterWhere['cid'] = array('eq', $customerId);
        $posterWhere['deleted'] = array('eq', 0);
        $posterWhere['status'] = array('eq', 1);
        $posterWhere['module'] = array('eq', 'product');
        $posterWhere['moduleId'] = array('eq', $pid);
        $posterCount = $posterModel->where($posterWhere)->count();
        $posterCount<=0 ? $result["isShowPoster"] = 0 : $result["isShowPoster"] = 1;
		//销售信息
		$param->currentUid = $userId;
		$result["contactInfo"] = Module::callModule("community", Session::$user,"getContactInfo", $param);
		$result['isShowLish']=1;
		if($result["miUId"]&&$result["miUId"]!=$userId){
			$result['isShowLish']=0;
		}
		$result=array_merge($result,$detail);
		$result['customizedTime']=date("Y-m-d")."T".date("H:i");
		$result['visitId']=$visitId;
		$result['lastShareUId']=$userId;
		Output::instance()->module("product",$tplHtmlName)->object($result);
	}
	public function crowdStall($id){
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$productModel = M("module_product");
		$productSpecModel = M("module_product_specification");
		Session::switchCustomer($customerId);
		$distribution = M("module_distribution_scheme");
		$productInfo = $productModel->alias("a")
			->join("wx_module_product_specification b on a.id=b.pid and a.supportSpecification=1")
			->join("wx_mishare c on c.module='product' and c.moduleId=a.id and c.deleted=0")
			->field("a.title,a.recommend,c.id as sId,a.id,a.vId,a.crowdStatus,a.proSource,a.distributionId,a.picUrl1,a.name,a.playType,a.inventoryCount,a.supportSpecification,a.inventory,a.fixedPrice,a.discountedPrice,min(b.fixedPrice) as minFixedPrice,
				max(b.fixedPrice) as maxFixedPrice,min(b.discountedPrice) as minDisPrice,max(b.discountedPrice) as maxDisPrice")
			->where("a.id = $id")
			->find();
		if($productInfo['picUrl1']){
			$productInfo['picUrl1'] = json_decode($productInfo['picUrl1'],true);
		}
		if(!$productInfo['distributionId']){
			$distriWhere['isDefault'] = array('eq',1);
			$distriWhere['deleted'] = array('eq',0);
			$distributionInfo = $distribution->where($distriWhere)->field('id')->find();
			$productInfo['distributionId'] = $distributionInfo['id'];
		}
		$stallList = $productSpecModel->alias("a")
			->join("inner join wx_module_product_crowdfunding b on a.firstSpecificId=b.specId and a.pid = b.pid")
			->field("min(a.fixedPrice) as minFixedPrice,max(a.fixedPrice) as maxFixedPrice,min(a.discountedPrice) as minDisPrice,max(a.discountedPrice) as maxDisPrice,a.firstSpecificName,a.firstSpecificUrl,b.*")
			->where("a.pid = $id")
			->group("a.firstSpecificId")
			->select();
		if ($productInfo["supportSpecification"] == 1) {
			$arrFirstSpec = $productSpecModel->alias("sepc")->where("pid=$id")->distinct("specificationName")
				->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
				->order("sepc.id")
				->getField("specificationName", true);
			$arrFirstSpecurl = $productSpecModel->alias("sepc")->where("pid=$id")->distinct("specificationName")
				->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
				->order("sepc.id")
				->getField("specificationUrl", true);
			if ($arrFirstSpec) {
				$result["sizeUnit"] = $productSpecModel->alias("sepc")->where("sepc.pid=$id")->distinct("specificationName")
					->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
					->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
					->getField("groupName");
			}
			$result["size"] = $arrFirstSpec;
			if ($arrFirstSpecurl) {
				$result["sizeurl"] = $arrFirstSpecurl;
			}
			$arrSecSpec = $productSpecModel->alias("sepc")->where("pid=$id")->distinct("specificationName")
				->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
				->getField("specificationName", true);
			$arrSecSpecurl = $productSpecModel->alias("sepc")->where("pid=$id")->distinct("specificationName")
				->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
				->getField("specificationUrl", true);

			if ($arrSecSpec) {
				$result["colorUnit"] = $productSpecModel->alias("sepc")->where("sepc.pid=$id")->distinct("specificationName")
					->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
					->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
					->getField("groupName");
			}
			$result["color"] = $arrSecSpec;
			if ($arrSecSpecurl) {
				$result["colorurl"] = $arrSecSpecurl;
			}
			$availSku = self::getProductInventory(array(
				"pid"=>$id,
				"arrFirstSpec"=>$arrFirstSpec,
				"arrSecSpec"=>$arrSecSpec
			));
			$result["availSku"] = json_encode($availSku);
		}
		$quanInfo = self::isPartner();
		$result['quanInfo']= $quanInfo;
		$result['productInfo']=$productInfo;
		$result['stallList']=$stallList;
		foreach($stallList as $key=>$value){
			unset($stallList[$key]['stallDescribe']);
		}
		$result['stallJson']=json_encode($stallList);
		$result['mallHue']=self::getMallHue();
		Output::instance()->module("product","product_common_crowdfunding_stall")->object($result);
	}
	//判断是否享有密友价
	private static function isEnjoyMiPrice($param){
		/*没有用上jie1101*/
		/* $customerId = Session::$user['customerId'];
		$userName = Session::$user['userName'];
		$uid = Session::$user["userId"];
		Session::switchCustomer(0);
		$mimallModel = M("mimall_user");
		$quanuserModel = M("quan_user");
		Session::switchCustomer($customerId);*/
		$qid = $param->qId;
		$miUid = $param->miUId;
		if(($qid&&$miUid)){
			return true;
		}
		$result = self::isPartner();
		if($result['qId']&&$result['uId']){
			return true;
		}
		return false;
//		$quanWhere['uid']=array('eq',$uid);
//		$quanWhere['stauts']=array('eq',1);
//		$quanWhere['deleted']=array('eq',0);
//		$result = $quanuserModel->where($quanWhere)->find();
//		if($result){
//			return true;
//		}

//		$where['openid'] = array('eq',$userName);
//		$result = $mimallModel->where($where)->find();
//		if($result){
//			return true;
//		}else{
//			return false;
//		}

	}
	private static function isPartner(){
		$customerId = Session::$user['customerId'];
		$uId=Session::$user['userId'];
		Session::switchCustomer(0);
		$quanModel = M("quan_user");
		Session::switchCustomer($customerId);
		$where["a.uid"]=array("eq",$uId);
		$where['a.deleted']=array("eq",0);
		$where["a.status"]=array("eq",1);
		$where['b.cId'] = array("eq",$customerId);
		$quanInfo = $quanModel->alias("a")
			->join("inner join wx_miyouquan b on a.qid =b.id")
			->where($where)
			->field("a.qid as qId,a.uid as uId,b.miAward")
			->find();
		return $quanInfo;
	}
	public static function startNewPeriod($pid,$totalCopies){
		$customerId = Session::$user['customerId'];
		$userName = Session::$user['userName'];
		Session::switchCustomer(0);
		$periodModule = M("module_mill_period");
		$parModule = M("module_mill_par");
		$numberModule = M("module_mill_number");
		Session::switchCustomer($customerId);
		$temp = $periodModule->where("pid=".$pid." and periodState = 1")->select();
		if($temp&&count($temp)){
			return;
		}
		$perNumber = $periodModule->where("pid=".$pid)->count();
		$perNumber++;
		$arr["pid"]=$pid;
		$arr["beenSold"]=0;
		$arr["surplus"]=$totalCopies;
		$arr["periodState"]=1;
		$arr["createTime"]=date('Y-m-d H:i:s',time());
		$arr["updataTime"]=date('Y-m-d H:i:s',time());
		$arr["fromCustomerId"] = $customerId;
		$arr["perNumber"] = $perNumber;
		$arr["id"] = $periodModule->add($arr);
		$arrData = array();
		for($i=1;$i<=$totalCopies;$i++){
			$data["perId"] = $arr["id"];
			$data["number"]=100000+$i;
			$data["pid"]=$pid;
			$data["createTime"]=date('y-m-d h:i:s',time());
			array_push($arrData,$data);
		}
		$numberModule->addAll($arrData);
		self::Additional($arr["id"],$pid,$totalCopies);
		return $arr["id"];
	}
	//追期处理
	public static function Additional($perId,$pid,$totalCopies){
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$parModule = M("module_mill_par");
		$periodModule = M("module_mill_period");
		Session::switchCustomer($customerId);
		//更改参与表信息
//		$where["a.parState"]=array("eq",0);
//		$where["a.pid"]=array("eq",$pid);
//		$where["b.status"] = array("eq",'partake');
		$data["perId"] = $perId;
		$data["updateTime"]=date('y-m-d H:i:s',time());
		$parList = $parModule->alias("a")
			->join("inner join wx_module_product_order b on a.oid = b.id")
			->field("a.*")
//			->where($where)
			->where("a.parState=0 and a.pid=$pid and (b.status = 'partake' or b.status = '".order_status_ok."' or b.status = '".order_status_delivered."' or b.status = '".order_status_refund."' or b.status = '".ORDER_STATUS_REFUNDEDPART."')")
			->order("a.id desc")
			->group("a.openId")
			->select();
		$periodInfo = $periodModule->where("id=".$perId)->field("surplus")->find();
		$surplus = $periodInfo["surplus"];
		foreach($parList as $key=>$value){
			if($surplus>=$value["count"]){
				//修改追期参与记录
				$data["parState"]=1;
				if($surplus==$value["count"]){
					$data["parState"]=2;
					$periodData["periodState"]=2;
					$periodData["updataTime"]=date('y-m-d H:i:s',time());
					$periodModule->where("id=".$perId)->save($periodData);
					Log::write("追期数量足够修改期表时间".$periodModule->getLastSql());
				}
				$parModule->where("id=".$value["id"])->save($data);
				Log::write("追期修改参与记录".$parModule->getLastSql());
				//追期的分配号码
				$surplus = self::indianaRandCode($value["count"],$perId,$value["id"],$value["openId"],$value["oid"],$pid,$totalCopies);
			}
		}
	}

	/**
	 * 获取多规格商品的库存 性能优化改动了嵌套查询 jie 1101
	 * @param $param
	 * @return array|null
	 */
	public static function getProductInventory($param) {
		$pid=$param["pid"];
		$arrFirstSpec=$param["arrFirstSpec"];
		$arrSecSpec=$param["arrSecSpec"];
		if ($arrFirstSpec == NULL && $arrSecSpec == NULL) {
			return NULL;
		}
		$availSku = array();
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$inventoryModel = M("module_product_specification");
		$productModel = M("module_product");
		Session::switchCustomer($customerId);
		$proInfo = $productModel->where("id=$pid")->field("isChainPro,supplyProId")->find();
		$allSpecList = $inventoryModel->where(['pid'=>$pid])->field("firstSpecificName,secSpecificName,fixedPrice,
		discountedPrice,miPrice,weight,inventoryCount,seckillInventoryCount,seckillPrice")->select();

		$chainRetArr = [];
		if($proInfo['isChainPro']){
			//将是供应链的所有库存量查询出来
			$chaninCountList = $inventoryModel->where(['pid'=>$proInfo['supplyProId']])->field("firstSpecificName,secSpecificName,inventoryCount")->select();
			foreach($chaninCountList as $k=>$v){
				$chainRetArr[$v['firstSpecificName'].$v['secSpecificName']] = $v['inventoryCount'];
			}
		}

		$inventory = [];
		if ($arrFirstSpec != NULL && $arrSecSpec != NULL) {
			foreach($allSpecList as $k=>$val){
				$inventory['fixedPrice'] = $val['fixedPrice'];
				$inventory['discountedPrice'] = $val['discountedPrice'];
				$inventory['miPrice'] = $val['miPrice'];
				$inventory['weight'] = $val['weight'];
				$inventory['inventoryCount'] = $val['inventoryCount'];
				$inventory['seckillInventoryCount'] = $val['seckillInventoryCount'];
				$inventory['seckillPrice'] = $val['seckillPrice'];
				if($proInfo['isChainPro']){
					$inventory['inventoryCount'] = $chainRetArr[$val['firstSpecificName'].$val['secSpecificName']];
				}
				$key = $val['firstSpecificName'] . '|' . $val['secSpecificName'];
				$availSku[$key] = $inventory;
			}
			/*foreach ($arrFirstSpec as $firstSepc) {
				foreach ($arrSecSpec as $secSepc) {
					$where["pid"] = $pid;
					$where["firstSpecificName"] = $firstSepc;
					$where["secSpecificName"] = $secSepc;
					$inventory = $inventoryModel->where($where)->field("fixedPrice,discountedPrice,miPrice,weight,inventoryCount,seckillInventoryCount,seckillPrice")->find();
					if($proInfo['isChainPro']){
						$where["pid"] = $proInfo['supplyProId'];
						$inventory['inventoryCount'] = $inventoryModel->where($where)->getField("inventoryCount");
					}
					$key = $firstSepc . '|' . $secSepc;
					$availSku[$key] = $inventory;
				}
			}*/
		} else if ($arrFirstSpec != NULL) {
			foreach($allSpecList as $k=>$val){
				$inventory['fixedPrice'] = $val['fixedPrice'];
				$inventory['discountedPrice'] = $val['discountedPrice'];
				$inventory['miPrice'] = $val['miPrice'];
				$inventory['weight'] = $val['weight'];
				$inventory['inventoryCount'] = $val['inventoryCount'];
				$inventory['seckillInventoryCount'] = $val['seckillInventoryCount'];
				$inventory['seckillPrice'] = $val['seckillPrice'];
				if($proInfo['isChainPro']){
					$inventory['inventoryCount'] = $chainRetArr[$val['firstSpecificName'].$val['secSpecificName']];
				}
				$availSku[$val['firstSpecificName']] = $inventory;
			}
			/*foreach ($arrFirstSpec as $firstSepc) {
				$where["pid"] = $pid;
				$where["firstSpecificName"] = $firstSepc;
				$inventory = $inventoryModel->where($where)->field("fixedPrice,discountedPrice,miPrice,weight,inventoryCount,seckillInventoryCount,seckillPrice")->find();
// 				echo $inventoryModel->getLastSql();
				if($proInfo['isChainPro']){
					$where["pid"] = $proInfo['supplyProId'];
					$inventory['inventoryCount'] = $inventoryModel->where($where)->getField("inventoryCount");
				}
				$availSku[$firstSepc] = $inventory;
			}*/
		} else if ($arrSecSpec != NULL) {
			foreach($allSpecList as $k=>$val){
				$inventory['fixedPrice'] = $val['fixedPrice'];
				$inventory['discountedPrice'] = $val['discountedPrice'];
				$inventory['miPrice'] = $val['miPrice'];
				$inventory['weight'] = $val['weight'];
				$inventory['inventoryCount'] = $val['inventoryCount'];
				$inventory['seckillInventoryCount'] = $val['seckillInventoryCount'];
				$inventory['seckillPrice'] = $val['seckillPrice'];
				if($proInfo['isChainPro']){
					$inventory['inventoryCount'] = $chainRetArr[$val['firstSpecificName'].$val['secSpecificName']];
				}
				$availSku[$val['secSpecificName']] = $inventory;
			}
			/*foreach ($arrSecSpec as $secSepc) {
				$where["pid"] = $pid;
				$where["secSpecificName"] = $secSepc;
				$inventory = $inventoryModel->where($where)->field("fixedPrice,discountedPrice,miPrice,weight,inventoryCount,seckillInventoryCount,seckillPrice")->find();
				if($proInfo['isChainPro']){
					$where["pid"] = $proInfo['supplyProId'];
					$inventory['inventoryCount'] = $inventoryModel->where($where)->getField("inventoryCount");
				}
				$availSku[$secSepc] = $inventory;
			}*/
		}

		return $availSku;
	}
	/**
	 * [getProductUnit 获取商品规格]
	 * @param  [type] $productList [description]
	 * @return [type]              [description]
	 */
	public function getProductUnit($productList){
		$userName = Session::$user['userName'];
		$customerId = Session::$user['customerId'];
		$newmipro=array();
		$customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
	    $specModel = M("module_product_specification");
	    Session::switchCustomer($customerId);
		$redis = new RedisAPI();
		foreach ($productList as $key=>$val){
	        $pid=$val['id'];
	        if ($val["supportSpecification"] == 1) {
				$arrFirstSpec = $redis->get('cid'.$customerId.'pid'.$pid.'firstSpec');
				if($arrFirstSpec){
					$arrFirstSpec = unserialize($arrFirstSpec);
				}else{
					$arrFirstSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
						->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
						->order("sepc.id")
						->getField("specificationName", true);
					$redis->set('cid'.$customerId.'pid'.$pid.'firstSpec', serialize($arrFirstSpec), 12*60*60);
				}

				$arrFirstSpecurl = $redis->get('cid'.$customerId.'pid'.$pid.'firstSpecUrl');
				if($arrFirstSpecurl){
					$arrFirstSpecurl = unserialize($arrFirstSpecurl);
				}else{
					$arrFirstSpecurl = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
						->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
						->order("sepc.id")
						->getField("specificationUrl", true);
					$redis->set('cid'.$customerId.'pid'.$pid.'firstSpecUrl', serialize($arrFirstSpecurl), 12*60*60);
				}


	            if ($arrFirstSpec) {
					$sizeUnit = $redis->get('cid'.$customerId.'pid'.$pid.'sizeUnit');
					if($sizeUnit){
						$sizeUnit = unserialize($sizeUnit);
					}else{
						$sizeUnit = $specModel->alias("sepc")->where("sepc.pid=$pid")->distinct("specificationName")
							->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
							->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
							->getField("groupName");
						$redis->set('cid'.$customerId.'pid'.$pid.'sizeUnit', serialize($sizeUnit), 12*60*60);
					}
					$val["sizeUnit"] = $sizeUnit;
	            }
	            if($arrFirstSpec){
					$val["size"] = json_encode($arrFirstSpec);
	            }
	            if ($arrFirstSpecurl) {
					$val["sizeurl"] = json_encode($arrFirstSpecurl);
				}

				$arrSecSpec = $redis->get('cid'.$customerId.'pid'.$pid.'arrSecSpec');
				if($arrSecSpec){
					$arrSecSpec = unserialize($arrSecSpec);
				}else{
					$arrSecSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
						->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
						->getField("specificationName", true);
					$redis->set('cid'.$customerId.'pid'.$pid.'arrSecSpec', serialize($arrSecSpec), 12*60*60);
				}

				$arrSecSpecurl = $redis->get('cid'.$customerId.'pid'.$pid.'arrSecSpecurl');
				if($arrSecSpecurl){
					$arrSecSpecurl = unserialize($arrSecSpecurl);
				}else{
					$arrSecSpecurl = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
						->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
						->getField("specificationUrl", true);
					$redis->set('cid'.$customerId.'pid'.$pid.'arrSecSpecurl', serialize($arrSecSpecurl), 12*60*60);
				}

	            if ($arrSecSpec) {
					$colorUnit = $redis->get('cid'.$customerId.'pid'.$pid.'colorUnit');
					if($colorUnit){
						$colorUnit = unserialize($colorUnit);
					}else{
						$colorUnit = $specModel->alias("sepc")->where("sepc.pid=$pid")->distinct("specificationName")
							->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
							->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
							->getField("groupName");
						$redis->set('cid'.$customerId.'pid'.$pid.'colorUnit', serialize($colorUnit), 12*60*60);
					}
					$val["colorUnit"] = $colorUnit;
	            }
	            if($arrSecSpec) {
	            	$val["color"] = json_encode($arrSecSpec);
	            }
	            if ($arrSecSpecurl) {
	            	$val["colorurl"] = json_encode($arrSecSpecurl);
	            }
	            if ($val["inventory"] == 1) {
	            	if (isset($arr['availSku'])) {
	                    $availSku=$arr['availSku'];
	                }else{
	                    /*$params["pid"] = $val['id'];
	                    $params["arrFirstSpec"] = $arrFirstSpec;
	                    $params["arrSecSpec"] = $arrSecSpec;
	                    $availSku = Module::callModule('product', NULL, 'getProductInventory', $params);*/
						self::getProductInventory(array(
							"pid"=>$val['id'],
							"arrFirstSpec"=>$arrFirstSpec,
							"arrSecSpec"=>$arrSecSpec
						));
	                }
	                $val["availSku"] = json_encode($availSku);
	            }
				if (!isset($val["availSku"])) {
					$val["availSku"] = json_encode(null);
				}
	        }
	        $mipro[$key]=$val;
	        $newmipro[$pid]=$val;
	    }
	    return $newmipro;
	}
	public static function getProductCategoryById($tplId, $cids, $start, $limit, $rootId = NULL) {
		$userName = Session::$user['userName'];
		$customerId = Session::$user['customerId'];
// 		Session::switchCustomer(0);

		$ProductCatModel = M("module_product_category");
//		if ($cids != '') {
//			$arrCondition = array();
//			$arrCid = explode(",", $cids);
//			foreach ($arrCid as $cid) {
//				array_push($arrCondition, array('eq', $cid));
//			}
//			array_push($arrCondition, 'or');
//			$where["cat.id"] = $arrCondition;
//		}

		$where["cat.isRemoved"] = 0;
		$where["cat.deleted"] = 0;
		$where["pdt.isRemoved"] = 0;
		$where["pdt.deleted"] = 0;
//
//
//        $list = array();
//        if($cids != ''){
//            $arrCid = explode(',',$cids);
//            $list['productList'] = array();
//            foreach($arrCid as $k => $v){
//                $where['cat.id'] = $v;
//                $arr = $ProductCatModel->alias("cat")->where($where)->join("wx_".$customerId."_module_product pdt ON cat.id = pdt.categoryId")
//                    ->field("pdt.*")->limit("$start, $limit")->order("number asc")->select();
//                $list['productList'][$k] = $arr;
//            }
//        }
		$arrTag = explode(',', $cids);
		$checkarr = false;
		$arr = null;
		foreach($arrTag as $k=>$v){
			if($v != ''){
				$where['cat.id'] = $v;
				$arr = $ProductCatModel->alias("cat")->where($where)->join("wx_".$customerId."_module_product pdt ON cat.id = pdt.categoryId")
					->field("pdt.*")->limit("$start, $limit")->order("number asc")->select();
				if($arr){
					$checkarr = true;
					$result['list'][$k]['productList'] = $arr;
				}
			}
		}

//        var_dump($list);
//        var_dump($result);
// 		echo $ProductCatModel->getLastSql();
		if (!$checkarr) {
			Output::instance()->resultCode(code_success);
			return;
		}
		$total = $ProductCatModel->alias("cat")->where($where)->join("wx_".$customerId."_module_product pdt ON cat.id = pdt.categoryId")->count();

		if (isset($rootId)) {
// 			Session::switchCustomer($customerId);
			$materialObjNav = self::getMaterialObj($rootId);
			if ($materialObjNav != NULL) {
				$nav = self::getNav($materialObjNav, $customerId, $userName, $rootId);
				$result["header"] = $nav["header"];
				$result["footer"] = $nav["footer"];
				$result["headerTpl"] = $nav["headerTpl"];
				$result["footerTpl"] = $nav["footerTpl"];
			}
// 			Session::switchCustomer(0);
		}

		if ($cids != '') {
			$cid = $arrTag[0];
			$banner = $ProductCatModel->where("id=$cid")->find();
			if ($banner) {
				$result["banner"] = $banner;
			}
		}

		// foreach($arr as $k => $v){
		// 	$discount = self::getDiscountPrice($v['id']);
		// 	$arr[$k]['discountedPrice']=$discount['discPrice'];
		// }

//		$result["productList"] = $arr;
		$result["total"] = $total;

		if ($userName == '') {
			$result["showBtn"] = 0;
		} else {
			$result["showBtn"] = 1;
		}

//        var_dump($result);
		switch ($tplId) {
			case 1:
				Output::instance()->module('product', 'product_common_list')->object($result);
				break;
			case 2:
				Output::instance()->module('product', 'product_single_list_selected')->object($result);
				break;
			case 4:
				Output::instance()->module('product', 'product_multi_list')->object($result);
				break;
			case 5:
				Output::instance()->module('product', 'product_multi_list_3column')->object($result);
				break;
		}

// 		Session::switchCustomer($customerId);
	}

	public static function getProductListByCategory($cid, $userName, $start = NULL, $limit = NULL) {
		$customerId = Session::$user["customerId"];
// 		Session::switchCustomer(0);

		$ProductModel = M("module_product");
		$where["categoryId"] = $cid;
		$where["isGroup"] = 0;
		$where["deleted"] = 0;
		if (!isset($start) || !isset($limit)) {
			$productList = $ProductModel->where($where)->order("number asc")->select();
		} else {
			$productList = $ProductModel->where($where)->order("number asc")->limit("$start, $limit")->select();
		}
		// 		echo $ProductModel->getLastSql();

		$total = $ProductModel->where($where)->count();
		// 		echo $ProductModel->getLastSql();

		$Detail = M("module_product_order_detail");
		$conditionDetail["oid"] = 0;
		$conditionDetail["fromUserName"] = $userName;
		$conditionDetail["type"] = type_buy;
		$detailList = $Detail->where($conditionDetail)->select();
		// 		echo $Detail->getLastSql();

		for ($i = 0; $i < count($productList); $i++) {
			$pid = $productList[$i]["id"];
			$count = 0;
			for ($j = 0; $j < count($detailList); $j++) {
				if ($detailList[$j]["pid"] == $pid) {
					$count = $detailList[$j]["count"];
					// remove it
					array_splice($detailList, $j, 1);
					break;
				}
			}

			$productList[$i]["count"] = $count;
		}

		// foreach($productList as $k => $v){
		// 	$discount = self::getDiscountPrice($v['id']);
		// 	$productList[$k]['discountedPrice']=$discount['discPrice'];
		// }

		$result["total"] = $total;
		$result["productList"] = $productList;
		Session::switchCustomer($customerId);

		return $result;
	}


	public static function getProductCategoryWithPdt($tplId, $cids, $start, $limit, $rootId) {
		$userName = Session::$user['userName'];
		$customerId = Session::$user['customerId'];
// 		Session::switchCustomer(0);
		$ProductCatModel = M("module_product_category");
		if ($cids != '') {
			$arrCondition = array();
			$arrCid = explode(",", $cids);
			foreach ($arrCid as $cid) {
				array_push($arrCondition, array('eq', $cid));
			}
			array_push($arrCondition, 'or');
			$where["cat.id"] = $arrCondition;
		}

		$where["cat.isRemoved"] = 0;
		$where["cat.deleted"] = 0;
		$where["pdt.isRemoved"] = 0;
		$where["pdt.deleted"] = 0;

		$arr = $ProductCatModel->alias("cat")->where($where)->field("cat.*")->distinct("cat.id")
			->join("wx_" . $customerId . "_module_product pdt ON cat.id = pdt.categoryId")->limit("$start, $limit")
			// 			->order("number asc")
			->select();
		// 				echo $ProductCatModel->getLastSql();
		if (!$arr) {
			Output::instance()->resultCode(code_success);
			return;
		}
		for($i = 0; $i < count($arr); $i++) {
			$categoryId = $arr[$i]["id"];
			$conditionDetail["cat.id"] = $categoryId;
			$conditionDetail["detail.oid"] = 0;
			$conditionDetail["detail.fromUserName"] = $userName;
			$conditionDetail["type"] = type_buy;
			$reserveCount = $ProductCatModel->alias("cat")->where($conditionDetail)
				->join("wx_" . $customerId . "_module_product product ON product.categoryId = cat.id")
				->join("wx_" . $customerId . "_module_product_order_detail detail ON detail.pid = product.id")->count("cat.id");
			// 						echo $ProductCatModel->getLastSql();
			$arr[$i]["reserveCount"] = $reserveCount;
		}

// 		Session::switchCustomer($customerId);
		if ($arr) {
			$result["tags"] = $arr;
			$productList = product::getProductListByCategory($arr[0]["id"], $userName);
			if ($productList) {
				$result["products"] = $productList;
			}
		}

		if ($userName == '') {
			$result["showBtn"] = 0;
		} else {
			$result["showBtn"] = 1;
		}
		// 页面中区别当前显示类别组产品还是标签组产品
		$result["groupBy"] = GROUP_CATEGORY;

		switch ($tplId) {
			case 4:
				Output::instance()->module('product', 'product_multi_list')->object($result);
				break;
			case 5:
				Output::instance()->module('product', 'product_multi_list_3column')->object($result);
				break;
		}
	}

	private static function getFavorite($userName, $start, $limit, $rootId = NULL) {
		$customerId = Session::$user['customerId'];
		$userId = Session::$user['userId'];

		$result = array();
		if (isset($rootId)) {
			$materialObjNav = self::getMaterialObj($rootId);
			if ($materialObjNav != NULL) {
				$nav = self::getNav($materialObjNav, $customerId, $userName, $rootId);
				$result["header"] = $nav["header"];
				$result["footer"] = $nav["footer"];
				$result["headerTpl"] = $nav["headerTpl"];
				$result["footerTpl"] = $nav["footerTpl"];
			}
		}

		Session::switchCustomer(0);
		$where["fav.fromCustomerId"] = $customerId;
//		$where["fav.fromUserName"] = $userName;
		$where["fav.uid"] = $userId;//LP修改


		$where["pdt.isRemoved"] = 0;
		$where["pdt.deleted"] = 0;
		$FavModel = M("module_product_favorite");
		$fav = $FavModel->alias("fav")
			->join("wx_module_product pdt ON fav.pid = pdt.id")
			->join("wx_module_product_specification spe on pdt.id=spe.pid")
			->where($where)
			->field("pdt.*,MIN(spe.discountedPrice) as minDisPrice,MAX(spe.discountedPrice) as maxDisPrice,
				MIN(spe.miPrice) as minMiPrice,MAX(spe.miPrice) as maxMiPrice,MAX(spe.fixedPrice) as maxFixedPrice,MIN(spe.fixedPrice) as minFixedPrice")
			->order("updateTime desc")
			->group("pdt.id")
			->limit($start, $limit)
			->select();
		foreach($fav as $key=>$value){
			$value['picUrl1']=json_decode($value['picUrl1'],true);
			if($value['picUrl1'][1]&&$value['picUrl1'][1]['picUrl']){
				$fav[$key]["picUrl"]=$value['picUrl1'][1]['picUrl'];
			}
		}
		if (!$fav) {
			return;
		}
		$total =$FavModel->alias("fav")->join("wx_module_product pdt ON fav.pid = pdt.id")->where($where)->count();
		Session::switchCustomer($customerId);
		$result["favorites"] = $fav;
		$result["total"] = $total;
		$result['isEnjoyMiPrice']=self::isEnjoyMiPrice(null)?1:0;
		return $result;
	}

	public static function getProductFavorite($tplid, $userName, $start, $limit, $rootId = NULL,$token=NULL) {
		$token = Module::callModule("personCenter",null,"verifyToken",$token);
		$result = self::getFavorite($userName, $start, $limit, $rootId);
		if ($result) {
			Output::instance()->module('product', 'product_common_favorite')->object($result);
		} else {
			Output::instance()->resultCode(code_product_favorite_none);
		}
	}

	public static function getProductFavoriteNext($userName, $start, $limit, $rootId = NULL) {
		$result = self::getFavorite($userName, $start, $limit, $rootId);
		if ($result) {
			Output::instance()->object($result);
		} else {
			Output::instance()->resultCode(code_product_favorite_none);
		}
	}

	public static function addFavorite($id,$token) {
		$token = Module::callModule("personCenter",null,"verifyToken",$token);
		$customerId = Session::$user['customerId'];
 		Session::switchCustomer(0);
		$userName = Session::$user['userName'];
		$userId = Session::$user['userId'];
		$FavModel = M("module_product_favorite");
		$data["fromCustomerId"] = $customerId;
		$data["uid"] = $userId;
		$data["pid"] = $id;
		$result = $FavModel->where($data)->find();

		$PdtModel = M("module_product");
		if (!$result) {
			$data["fromUserName"] = $userName;
			$data["updateTime"] = date("Y-m-d H:i:s");
			$result = $FavModel->add($data);

			$PdtModel->where("id=$id")->setInc('favoriteCount');

			$PdtHisModel = M("module_product_favorite_histroy");
			$PdtHisModel->add($data);
		}
		if ($result) {
			$pdt = $PdtModel->where("id=$id")->find();
			if($pdt){
				$detail = $pdt['name'];
			}else{
				$detail='';
			}
			Session::switchCustomer($customerId);

			set_point_by_point_type(module_handle_favoriteProduct, $userName,false,$detail);
			Output::instance()->resultCode();
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	public static function removeFavorite($id, $userName) {
		$customerId = Session::$user['customerId'];
		$userId = Session::$user['userId'];
 		Session::switchCustomer(0);
		$FavModel = M("module_product_favorite");
		$where["fromCustomerId"] = $customerId;
//		$where["fromUserName"] = $userName;
		$where["uid"] = $userId;	//LP修改
		$where["pid"] = $id;
		$result = $FavModel->where($where)->delete();
		if ($result) {
			$PdtModel = M("module_product");
			$PdtModel->where("id=$id")->setDec('favoriteCount');

			$PdtHisModel = M("module_product_favorite_histroy");
			$where["updateTime"] = date("Y-m-d H:i:s");
			$where["isDelete"] = 1;
			$PdtHisModel->add($where);

			Output::instance()->resultCode();
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
 		Session::switchCustomer($customerId);
	}

	private static function getMaterialObj($id) {
		$MaterialModel = D("Material");

		$map["id"] = $id;
		$material = $MaterialModel->where($map)->find();
		if (!$material) {
			Output::instance()->resultCode(code_custom_error, '该主页不存在');
			return NULL;
		}
		$material = (object)$material;
		if (strcmp($material->module, 'webSite') != 0) {
			Output::instance()->resultCode(code_custom_error, '该主页不存在');
			return NULL;
		}
		$materialObj = simplexml_load_string($material->xml,
			'SimpleXMLElement', LIBXML_NOCDATA);
		return $materialObj;
	}

	private static function getNav($materialObjNav, $cid, $userName, $id) {
		$cid = Session::$user["customerId"];
		Session::switchCustomer($cid);
		$navTop = array();
		$navTopXml = $materialObjNav->NavTop;
		if ($navTopXml->item) {
			foreach ($navTopXml->item as $item) {
				$arrItem = array();
				$arrItem['title'] = $item->title;
				$arrItem['url'] = self::getTpl(get_session_url($item->url, $cid, $userName), $id);
				$arrItem['picurl'] = $item->picurl;
				array_push($navTop, $arrItem);
			}
		}

		$navBot = array();
		$navBotXml = $materialObjNav->NavBottom;
		if ($navBotXml->item) {
			foreach ($navBotXml->item as $item) {
				$arrItem = array();
				$arrItem['title'] = $item->title;
				$arrItem['url'] = self::getTpl(get_session_url($item->url, $cid, $userName), $id);
				$arrItem['picurl'] = $item->picurl;
				array_push($navBot, $arrItem);
			}
		}

		$headerId = (int)$materialObjNav->navtoptemplateid;
		if ($headerId != 0) {
			$arr['headerTpl'] = WEBSITE_TEMPLATE. 'header_' . $headerId . '.html';
		}
		$footerId = (int)$materialObjNav->navbottomtemplateid;
		if ($footerId != 0) {
			$arr['footerTpl'] = WEBSITE_TEMPLATE. 'footer_' . $footerId . '.html';
		}

		$arr['header'] = $navTop;
		$arr['footer'] = $navBot;
		Session::switchCustomer(0);
		return $arr;
	}

	private static function getTpl($url, $rootId) {
		$urlParam = strstr($url, 'params');
		if ($urlParam) {
			$arrParam = explode("&", $urlParam);
			$params = $arrParam[0];
			$endCharacter = '';
			if (strstr($params, '%7d')) {
				$endCharacter = '%7d';
			} else if (strstr($params, '%7D')) {
				$endCharacter = '%7D';
			} else if (strstr($params, '}')) {
				$endCharacter = '}';
			}
			if ($endCharacter != '') {
				$parentTpl =  ",%22rootid%22:" . $rootId . $endCharacter;
				$url = str_replace($endCharacter, $parentTpl, $url);
			}
		} else {
			if ($url != '') {
				$url = $url . "&params={%22rootid%22:" . $rootId . "}";
			}
		}
		return $url;
	}

	public static function getPickUp($oid){
		$userName = Session::$user["userName"];
		$userId = Session::$user["userId"];
		$UserInfo = get_UserInfo_by_fromUserName($userId);	//LP修改
        if (!$UserInfo) {
            $user_model = M('user');
            $UserInfo = $user_model->where(['id' => $userId])->find();
        }
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$storeModel = M("store");
		$orderModel = M("module_product_order");
		Session::switchCustomer($customerId);

		$deliveryInfo = $orderModel->alias("a")
			->join("inner join wx_".$customerId."_module_distribution_scheme b on a.distributionId=b.id")
			->join("inner join wx_".$customerId."_module_mall_delivery_type c on c.distributionId=b.id")
			->where("a.id=$oid and c.deliveryTypeValue='pickup'")
			->field("c.categoryIds")
			->find();
		$categoryIds = explode(",",$deliveryInfo['categoryIds']);
		if($UserInfo) {
			$result["fullName"] = $UserInfo["fullName"];
			$result["phone"] = $UserInfo["phone"];
			$result["address"] = $UserInfo["address"];
			if($UserInfo["lastBuyStoreId"]){
				$storeWhere["a.id"]=array("eq",$UserInfo["lastBuyStoreId"]);
				$storeWhere["a.deleted"]=array('eq',0);
				$storeWhere["a.isPickUp"]=array('eq',1);
				$result['storeInfo'] = $storeModel->alias("a")
					->join("inner join wx_store_district b on a.districtId=b.id")
					->where($storeWhere)->field("a.id,a.name,a.phone,a.address,a.contact,a.picUrl,b.districtCategoryId")
					->find();
				if(!in_array($result['storeInfo']['districtCategoryId'],$categoryIds)){
					unset($result['storeInfo']);
				}
			}
		}
		$result['oid']=$oid;
		$result['userName']=$userName;
		$result['mallHue']=self::getMallHue();
		Output::instance()->module("product","product_common_pickup")->object($result);
	}
	public static function getAddr($userName, $rootId,$tplId) {
		$userId = Session::$user["userId"];
		$UserInfo = get_UserInfo_by_fromUserName($userId);		//LP修改
		$customerId = Session::$user['customerId'];
		if (isset($rootId)) {
			$materialObjNav = self::getMaterialObj($rootId);
			if ($materialObjNav != NULL) {
				$nav = self::getNav($materialObjNav, $customerId, $userName, $rootId);
				$result["header"] = $nav["header"];
				$result["footer"] = $nav["footer"];
				$result["headerTpl"] = $nav["headerTpl"];
				$result["footerTpl"] = $nav["footerTpl"];
			}
		}

		if ($UserInfo) {
			$result["fullName"] = $UserInfo[user_full_name];
			$result["phone"] = $UserInfo[user_phone];
			$result["address"] = $UserInfo[user_address];
		}
		switch ($tplId) {
			case 1:
				Output::instance()->module('product', 'product_common_addr')->object($result);
				break;
			case 2:
				Output::instance()->module('product', 'product_single_detail_order_address_selected')->object($result);
				break;
			case 3:
				Output::instance()->module('product', 'product_single_detail_order_address')->object($result);
				break;
			case 4:
				Output::instance()->module('product', 'product_common_addr')->object($result);
				break;
		}
	}

	public static function getPickupStoreList($oid,$code,$parentId,$sort,$name) {
		$userName = Session::$user['userName'];
		$userId = Session::$user['userId'];
		$UserInfo = get_UserInfo_by_fromUserName($userId);	//LP修改
		$customerId = Session::$user['customerId'];
		if (isset($rootId)) {
			$materialObjNav = self::getMaterialObj($rootId);
			if ($materialObjNav != NULL) {
				$nav = self::getNav($materialObjNav, $customerId, $userName, $rootId);
				$result["header"] = $nav["header"];
				$result["footer"] = $nav["footer"];
				$result["headerTpl"] = $nav["headerTpl"];
				$result["footerTpl"] = $nav["footerTpl"];
			}
		}

		if ($UserInfo) {
			$result["lastBuyStoreName"] = $UserInfo[user_last_buy_store_name];
		}
		Session::switchCustomer(0);
		$orderModel =M("module_product_order");
		$storeDistrict = M('store_district');
		$storeModel = M("store");
		Session::switchCustomer($customerId);
		$deliveryInfo = $orderModel->alias("a")
			->join("inner join wx_".$customerId."_module_distribution_scheme b on a.distributionId=b.id")
			->join("inner join wx_".$customerId."_module_mall_delivery_type c on c.distributionId=b.id")
			->where("a.id=$oid and c.deliveryTypeValue='pickup'")
			->field("c.categoryIds")
			->find();
		$categoryIds = explode(",",$deliveryInfo['categoryIds']);
		$where['fromCustomerId']=array('eq',$customerId);
		$where['deleted']=array('eq',0);
		if($code){
			$where['code']=array('like',$code."%");
		}
		$where['districtCategoryId']=array("in",$categoryIds);
		$storeInfo = $storeDistrict->where($where)->field('group_concat(id) as ids')->find();
		$storeInfo['ids']?$storeWhere['districtId'] =array('in',explode(',',$storeInfo['ids'])):"";
		$storeWhere['a.customerId'] = array('eq',$customerId);
		$storeWhere['a.deleted']=array('eq',0);
		$storeWhere['a.isPickUp']=array('eq',1);
		$storeWhere['b.districtCategoryId']=array("in",$categoryIds);
		$storeWhere['_string']="a.name like '%$name%' or a.phone like '%$name%' or a.address like '%$name%'";
		$storeList = $storeModel->alias("a")
			->join("inner join wx_store_district b on a.districtId = b.id")
			->where($storeWhere)->field("a.id,a.name,a.phone,a.address,a.contact,a.picUrl,a.province,a.city,a.country")
			->order("a.$sort desc")->select();
		unset($where['code']);
		if($parentId){
			$where['parentId']=array('eq',$parentId);
		}else{
			$where['parentId']=array('exp','is null');
			$parentInfo = $storeDistrict->where($where)->field("id")->find();
			$where['parentId']=array('eq',$parentInfo["id"]);
		}

		$distristList = $storeDistrict->where($where)->order('updateTime desc')->select();
		$result['distristList']=$distristList;
		$result['storeList']=$storeList;
		if ($distristList === false) {
			Output::instance()->resultCode(code_store_pickup_not_exist);
			return;
		}
		Output::instance()->object($result);
	}




	public static function getAddrSign($url){
		$customerId = Session::$user['customerId'];

		$userName = Session::$user['userName'];
		$accessToken = WeixinApi::getUserOauthAccessToken($userName);
		if (!isset($accessToken)) {
			return;
		}

		$setting = R("CUser/getMallSetting");
		if (!$setting) {
			return;
		}

		$appid = $setting["appId"];
		if(!isset($appid) && !isset($accessToken)){
			return;
		}

		$wxPayHelper = new WxPayHelper();
		$result = $wxPayHelper->create_addr_sign($appid, $url, $accessToken);
		Output::instance()->object($result);
	}
	private static function getUrl($url) {
		$urlParam = strstr($url, 'params');
		if(strstr($urlParam, '%7B')){
			$urlParam = str_replace("%7B", "{", $urlParam);
			$urlParam = strstr($urlParam,"{");
			$url = strstr($url,"%7B",true);
		}
		if(strstr($urlParam, '%7D')){
			$urlParam = str_replace("%7D", "}", $urlParam);
		}
		if(strstr($urlParam, '%7D')){
			$urlParam = str_replace("%7D", "}", $urlParam);
		}
		if(strstr($urlParam, '%22')){
			$urlParam = str_replace("%22", "\"", $urlParam);
		}
		if(strstr($urlParam, '%3A')){
			$urlParam = str_replace("%3A", ":", $urlParam);
		}
		if(strstr($urlParam, '%2C')){
			$urlParam = str_replace("%2C", ",", $urlParam);
		}
		$param= json_decode($urlParam);
		$result["param"] = $param;
		$result["url"] = $url;
		return $result;
	}
	public static function getOrderSuccess($ids,$sendId) {
		$customerId = Session::$user["customerId"];
		$username = Session::$user["userName"];
		Session::switchCustomer($customerId);
		$mallModel=M("module_mall_store");
		$userModel = M("user");
		Session::switchCustomer(0);
		$couponSend = M("module_coupon_send");
		$userCoupon = M("module_user_coupon");
		$idArray = explode(',', $ids);
		if (count($idArray) > 1) {
			$whereArray = array();
			foreach ($idArray as $id) {
				array_push($whereArray, array('eq', intval($id)));
			}
			array_push($whereArray, 'OR');
			$whereOrder["id"] = $whereArray;
		} else {
			$whereOrder["id"] = $ids;
		}
		$mallResult=$mallModel->find();

		$OrderModel = M("module_product_order");
		$order = $OrderModel->where($whereOrder)->select();
		if($mallResult['storeurl']&&$order[0]["qId"]&&$order[0]["miUid"]){
			$mllResult = self::getUrl($mallResult['storeurl']);
			$param = $mllResult["param"];
			$param->qId = $order[0]["qId"];
			$param->miUId = $order[0]["miUid"];
			$mallResult['storeurl'] = $mllResult["url"].urlencode(json_encode($param));
		}
		if (!$order) {
			Output::instance()->resultCode(code_product_order_not_exist);
			return;
		}
		$userInfo = $userModel->where("userName='".$username."'")->find();
		if($userInfo["status"]=='unsubscribe'){
			$result["subscribe"] = 0;
		}else{
			$result["subscribe"] = 1;
		}
		$result["serialNumber"] = $order[0]["serialNumber"];
		$result['price'] = floatval(0);
		$result['points'] = 0;
		$result['logisticCost'] = floatval(0);
		foreach($order as $k => $v){
			$result['price'] += $v['price'];
			$result['points'] += $v['points'];
			$result['logisticCost'] += $v['logisticsCost'];
		}
		$payType = $order[0]["payType"];

		$result["payTypeName"] = R("Product/getOrderPayTypeName", array($payType));
		switch ($payType) {
			case ORDER_PAYTYPE_CONSUME:
				$result["payType"] = "消费积分";
				break;
			case ORDER_PAYTYPE_INTERACT:
				$result["payType"] = "互动积分";
				break;
			case ORDER_PAYTYPE_WXPAY:
				// 总价格未更新
				if ($order["status"] == order_status_notsubmit
					|| $order["stuats"] == ORDER_STATUS_PAYING) {
					$result["price"] += $result['logisticCost'];
				}
				self::updateOrderPayingConfirm($ids);
				break;
		}
		if($sendId){
			$sendInfo = $couponSend->alias("a")
				->join("inner join wx_module_coupon_scheme b on a.schemeId=b.id")
				->field("a.id,a.copiesPrice,a.surplusPrice,a.copiesNum,a.surplusNum,b.config,b.shareTitle,b.shareImg,b.shareDescribe,b.receiveType")
				->where("a.id=$sendId")
				->find();
			if($sendInfo['config']){
				$sendInfo['config']=json_decode($sendInfo['config'],true);
			}
			$result['sendInfo']=$sendInfo;
		}
		$result["mall"]=$mallResult;
		$result["ids"]=$ids;
		Session::switchCustomer($customerId);
		$result['mallHue']=self::getMallHue();
		$result['browser']=isMicroMessengerUserAgent()?1:0;
		if($order[0]['isActivity']&&!$sendId){
			Output::instance()->module('product', 'product_success')->object($result);
		}else{
			Output::instance()->module('product', 'product_order_success')->object($result);
		}
	}
	public static function virtualSuccess($oid){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$orderModel = M("module_product_order");
		Session::switchCustomer($customerId);
		$proInfo = $orderModel->alias("a")
			->join("inner join wx_module_product_order_detail b on a.id =b.oid")
			->join("inner join wx_module_product c on b.pid=c.id")
			->join("inner join wx_".$customerId."_module_verify_code d on a.id = d.oid")
			->field("c.id,c.virtualInfo,c.virtualStartTime,c.virtualEndTime,b.discountedPrice,b.fixedPrice,b.name,b.picUrl,GROUP_CONCAT(d.code) as code,GROUP_CONCAT(d.isClaim) as isClaim")
			->where("a.id=$oid")
			->group("a.id")
			->find();
		if($proInfo){
			$code=explode(",",$proInfo["code"]);
			$proInfo["isClaim"]=explode(",",$proInfo["isClaim"]);
			foreach($code as $key=>$value){
				$code[$key]=self::num_format($value," ");
			}
			if(!strtotime($proInfo["virtualEndTime"])){
				$proInfo["virtualTime"]=1;
			}else{
				$proInfo["virtualStartTime"]=date("Y年m月d日",strtotime($proInfo["virtualStartTime"]));
				$proInfo["virtualEndTime"]=date("Y年m月d日",strtotime($proInfo["virtualEndTime"]));
			}
			$proInfo["code"]=$code;
		}
		Output::instance()->module('product', 'product_virtual_success')->object($proInfo);
	}

	/**充值卡商品成功页面
	 * @param $oid
	 */
	public static function rechargeableCardSuccess($oid)
	{
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$orderModel = M("module_product_order");
		$orderDetailModel = M('module_product_order_detail');
		Session::switchCustomer($customerId);
		$proInfo = $orderModel->alias("a")
			->join("inner join wx_module_product_order_detail b on a.id =b.oid")
			->join("inner join wx_module_product c on b.pid=c.id")
			->field("c.id, b.rechargeableCard, b.discountedPrice, b.fixedPrice,b.name, b.picUrl")
			->where("a.id=$oid")
			->group("a.id")
			->find();
		$orderDetail = $orderDetailModel->where("oid = $oid")->select();
		$sumMoney = 0;
		foreach ($orderDetail as $item) {
			$rechargeableCard = $item['rechargeableCard'];//是否为充值卡
			if ($rechargeableCard == 1) { //商品是充值卡类型
				$rechargeAmount = $item['rechargeAmount']; //获取充值卡金额
				$cardCount = $item['count']; //获取购买数量
				$Money = $rechargeAmount * $cardCount; //充值金额为两数相乘
				$sumMoney = $sumMoney + $Money;
			}
		}
		$proInfo['sumMoney'] = $sumMoney;
		Output::instance()->module('product', 'product_rechargeableCard_success')->object($proInfo);
	}
	private static function updateOrderPayingConfirm($ids) {
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$idArray = explode(',', $ids);
		if (count($idArray) > 1) {
			$whereArray = array();
			foreach ($idArray as $id) {
				array_push($whereArray, array('eq', intval($id)));
			}
			array_push($whereArray, 'OR');
			$whereOrder["id"] = $whereArray;
		} else {
			$whereOrder["id"] = $ids;
		}
		$OrderModel = M("module_product_order");
		$orderList = $OrderModel->where($whereOrder)->select();
		foreach ($orderList as $order) {
			if (!$order || $order["status"] != order_status_notsubmit
				|| $order["status"] != ORDER_STATUS_PAYING) {
				return;
			}
			$data["updateTime"] = date("Y-m-d H:i:s");
			$data["status"] = order_status_payingconfirm;
			$OrderModel->execute("LOCK TABLES __TABLE__ WRITE");
			$id = $order["id"];
			$OrderModel->where("id=$id")->save($data);
			$OrderModel->execute("UNLOCK TABLES");
		}
		Session::switchCustomer($customerId);
	}
	public static function updateWeixinAddress($fullName,$phone,$province,$city,$country,$address,$isAcitivity){
		$UserReceiverAddress = M('user_receiver_address');
		$userInfoModel = M("user_info");
		$userName = Session::$user['userName'];
		$userInfo = $userInfoModel->where("fromUserName='$userName'")->find();
		$where['deleted']=array("eq",0);
		$where['userName']=array("eq",$userName);
		$where['receiverName']=array("eq",$fullName);
		$where['phone']=array("eq",$phone);
		$where['province']=array("eq",$province);
		$where['city']=array("eq",$city);
		$where['country']=array("eq",$country);
		$where['address']=array("eq",$address);
		$where['isAcitivity']=array("eq",$isAcitivity);
		$result = $UserReceiverAddress->where($where)->find();
		if(!$result){
			$UserReceiverAddress->where("userName='$userName' and deleted=0 and isDefault=1")->setField("isDefault",0);
			$data['userName']=$userName;
			$data['receiverName']=$fullName;
			$data['phone']=$phone;
			$data['province']=$province;
			$data['city']=$city;
			$data['country']=$country;
			$data['address']=$address;
			$data['isAcitivity']=$isAcitivity;
			$data['isDefault']=1;
			$data['createTime']=date("Y-m-d H:i:s");
			$data['updateTime']=date("Y-m-d H:i:s");
			$id = $UserReceiverAddress->add($data);
		}else{
			$id = $result['id'];
			$data['isDefault']=1;
			$condition['id']=array("eq",$id);
			$UserReceiverAddress->where($condition)->save($data);
		}
		$userData['fromUserName']=$userName;
		$userData['fullName']=$fullName;
		$userData['phone']=$phone;
		$userData['address']=$address;
		$userData['lastAddressId']=$id;
		$userData['lastDeliveryType']='delivery';
		if($userInfo){
			$userInfoModel->where("id=".$userInfo['id'])->save($userData);
		}else{
			$userInfoModel->add($userData);
		}
		Output::instance()->resultCode();
	}
	public static function updateUserInfo($userName, $fullName, $phone, $address, $storeId, $storeName,$deliveryType,$IDName,$IDNumber,$IDPositive,$IDBack, $oId = '') {
		$userId = Session::$user['userId'];
		$cid = Session::$user['customerId'];
		$userInfo = get_UserInfo_by_fromUserName($userId);//LP修改
		if($userInfo){
			$userFullName = $userInfo[user_full_name];
			$userphone = $userInfo[user_phone];
			$useraddress = $userInfo[user_address];
			$userstoreId = $userInfo[user_last_buy_store_id];
			$userstoreName = $userInfo[user_last_buy_store_name];
			$userdeliveryType = $userInfo["lastDeliveryType"];
			$userIDName = $userInfo['IDName'];
			$userIDNumber = $userInfo['IDNumber'];
			$userIDPositive = $userInfo['IDPositive'];
			$userIDBack = $userInfo['IDBack'];
		}else{
			$userFullName = '';
		}
		if (isset($fullName) && $fullName != '' && $fullName != $userFullName) {
			update_UserInfo_by_message($userId, $fullName, user_full_name);
		}
		if (isset($phone) && $phone != '' && $phone != $userphone) {
			update_UserInfo_by_message($userId, $phone, user_phone);
		}
		if (isset($address) && $address != '' && $address != $useraddress) {
			update_UserInfo_by_message($userId, $address, user_address);
		}
		if (isset($storeId) && $storeId != '' && $storeId != $userstoreId) {
			update_UserInfo_by_message($userId, $storeId, user_last_buy_store_id);
		}
		if (isset($storeName) && $storeName != '' && $storeName != $userstoreName) {
			update_UserInfo_by_message($userId, $storeName, user_last_buy_store_name);
		}
		if (isset($deliveryType) && $deliveryType != '' && $deliveryType != $userdeliveryType) {
			update_UserInfo_by_message($userId, $deliveryType, "lastDeliveryType");
		}
		if (isset($IDName) && $IDName != '' && $IDName != $userIDName) {
			update_UserInfo_by_message($userId, $IDName, "IDName");
		}
		if (isset($IDNumber) && $IDNumber != '' && $IDNumber != $userIDNumber) {
			update_UserInfo_by_message($userId, $IDNumber, "IDNumber");
		}
		if (isset($IDPositive) && $IDPositive != '' && $IDPositive != $userIDPositive) {
			update_UserInfo_by_message($userId, $IDPositive, "IDPositive");
		}
		if (isset($IDBack) && $IDBack != '' && $IDBack != $userIDBack) {
			update_UserInfo_by_message($userId, $IDBack, "IDBack");
        }
		//<侯佳添加2018-04-23，更新订单及地址信息>
		if ($oId) {
			Session::switchCustomer(0);
			$order_model = M('module_product_order');
			Session::switchCustomer($cid);
			$address_model = M('user_receiver_address');

            if (isset($deliveryType) && $deliveryType != '') {
                $data['deliveryType'] = $deliveryType;
            }

            if (isset($storeId) && $storeId != '') {
                $data['storeResourceId'] = $storeId;
            }
			$data['fullName'] = $fullName;
			$data['phone'] = $phone;
			$res = $order_model->where(['id' => $oId])->save($data);
			$address_model->where(['uid' => $userId])->save(['receiverName' => $fullName, 'phone' => $phone]);
		}
		//</侯佳添加2018-04-23，更新订单信息>
        return $userInfo;
    }

	public static function cancelOrder($id) {
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$OrderModel = M("module_product_order");

		$where["id"] = $id;
		$order = $OrderModel->where($where)->find();
		if (!$order) {
			Output::instance()->resultCode(code_product_order_not_exist);
			return;
		}
		if ($order["status"] != NULL && $order["status"] !== order_status_notsubmit
			&& $order["status"] != ORDER_STATUS_PAYING
			&& $order["payType"] != ORDER_PAYTYPE_DELIVERIY_PAY) {
			Output::instance()->resultCode(code_product_order_submitted);
			return;
		}
		if ($order["fromUserName"] != Session::$user["userName"]) {
			Output::instance()->resultCode(code_product_order_access_denied);
			return;
		}

		// 微信支付、一键支付，未提交、已提交未支付的不需要处理库存和销量问题
		if ($order["status"] !== order_status_notsubmit && $order["status"] !== ORDER_STATUS_PAYING
			&& $order["payType"] !== ORDER_PAYTYPE_UPAY
			&& $order["payType"] !== ORDER_PAYTYPE_WXPAY
            && $order["payType"] !== ORDER_PAYTYPE_TENPAY) {
			R('Product/revertProductInventory', array($id));
			R('Product/deductProductSalesCount', array($id));
		}

		$data["deleted"] = 1;
		$data["status"] = ORDER_STATUS_CLOSED;
		$result = $OrderModel->where($where)->save($data);
		if ($result !== false) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
		Session::switchCustomer($customerId);
	}

	public static function orderRefund($ids){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$orderRefund = m("module_product_order_feedback");
		$order = m("module_product_order");
		Session::switchCustomer($customerId);
		$data['fromUserName'] = Session::$user['userName'];
		$idArray = explode(',', $ids);
		foreach ($idArray as $id) {
			$where['id'] = $id;
			$orderArr = $order->where($where)->find();
			$data['wxTransactionId'] = $orderArr['wxTransactionId'];
			$data['orderId'] = $id;
			$data['msgType'] = 'request';
			$data['createTime'] = date('Y-m-d H:i:s');
			$result = $orderRefund->add($data);
			R('Product/revertProductInventory', array($id));
			R('Product/deductProductSalesCount', array($id));
			if(!$result) {
				Output::instance()->resultCode(code_sql_error);
				return;
			}
			$where['id'] = $id;
			$order->where($where)->setField('status', ORDER_STATUS_REFUNDING);
		}
		Output::instance()->resultCode();
	}
	/**
	 * [getcomment 评论页面]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function getcomment($param){
		$customerId = Session::$user["customerId"];
		$userName= Session::$user["userName"];
		Session::switchCustomer(0);
		$ProductOrderModel = M("module_product_order");
		Session::switchCustomer($customerId);
		$pid=$param->pid;
		$oid=$param->oid;
        $type=$param->type;
		$condition['b.pid']=$pid;
		$condition['a.id']=$oid;
		$condition['a.deleted']=0;
		$result=$ProductOrderModel->alias('a')
			->join("inner JOIN wx_module_product_order_detail b on b.oid = a.id")
			->join("inner JOIN wx_module_product c on c.id = b.pid")
			->join("wx_module_product_order_detail_specification spec ON spec.did=c.id")
			->where($condition)
			->field('a.*,a.id as oid,c.id as pid,b.count,c.name,c.fromCustomerId,c.picUrl1,spec.firstSpecificName as sizeName, spec.secSpecificName as colorName')
			->find();
			if($result['picUrl1']){
				$img=json_decode($result['picUrl1'],true);
				$result['picUrl'] = $img[1]['picUrl'];
			}
			unset($result['picUrl1']);
			$result['commentType']=$type;
		if($result){
			Output::instance()->module("product","product_common_comment")->object($result);
		}else{
			Output::instance()->resultCode(code_product_comment_none);
		}

	}
	/**
	 * [saveComment 保存评论]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function saveComment($param){
		$customerId = Session::$user["customerId"];
		$userName= Session::$user["userName"];
		Session::switchCustomer(0);
		$ProductCommentModel = M("module_product_comment");
		$orderModel = M("module_product_order");
		$configModel = M("module_comment_config");
		$orderDetail = M("module_product_order_detail");
		$pid=$param->pid;
		$oid=$param->oid;
		$imgUrls = $param->imgs;
		$comment=$param->comment;
        $type=$param->type;
        !$type?$type=0:$type=1;
        $orderInfo = $orderModel->where("id=$oid")->field("fromUserName,fromCustomerId")->find();
        $userName = $orderInfo['fromUserName'];
        $customerId = $orderInfo['fromCustomerId'];
        Session::switchCustomer($customerId);
        $userInfo = M("user_weixin_info");
		$condition['pid']=$pid;
		$condition['oid']=$oid;
		$condition['fromCustomerId']=$customerId;
		$condition['fromUserName']=$userName;
		$condition['type']=$type;
		$result=$ProductCommentModel->where($condition)->find();
		$fullname = $userInfo->where("openid=".$userName)->field("nickname")->find();

		if($result && count($result) > 0){
			//用户对改订单的商品已经评论过了。
			Output::instance()->resultCode(1,"已经评论过了！");
			return;
		} else {
			$addData=array(
				"oid"=>$oid,
				"pid"=>$pid,
				"comment"=>$comment,
				"fromCustomerId"=>$customerId,
				"fromUserName"=>$userName,
				"replyId"=>0,
				"status"=>0,
				"fullName"=>"",
				"deleted"=>0,
				"isComment"=>1,
				"fullname"=>$fullname,
				"createTime"=>date("Y-m-d H:i:s"),
				"imgurl"=>$imgUrls,
                "type"=>$type
			);
			$result=$ProductCommentModel->add($addData);
            $configInfo = $configModel->where("customerId=$customerId")->find();
            $detailList = $orderDetail->where("oid=$oid and pid=$pid")->field("price,count")->select();
            $redPrice = 0;
            foreach($detailList as $index=>$detailInfo){
                if($type==1){
                    if($imgUrls){
                        if($configInfo['communityAutomatic']==1){
                            if($detailInfo['price']>$configInfo['singleProductAmount']){
                                $redPrice += $configInfo['communityRedMoney']*$detailInfo['count'];
                            }else if($detailInfo['price']*$detailInfo['count']>$configInfo['singleProductAmount']){
                                $redPrice += $configInfo['communityRedMoney'];
                            }
                        }
                    }
                }else{
                    if($comment&&$imgUrls){
                        if($configInfo['mallAutomatic']==1){
                            if($detailInfo['price']>$configInfo['singleProductAmount']){
                                $redPrice += $configInfo['mallRedMoney']*$detailInfo['count'];
                            }else if($detailInfo['price']*$detailInfo['count']>$configInfo['singleProductAmount']){
                                $redPrice += $configInfo['mallRedMoney'];
                            }
                        }
                    }
                }
            }
            if($redPrice>0){
                if($type==1){
                    $wish = $configInfo['communityRedWish'];
                }else{
                    $wish = $configInfo['mallRedWish'];
                }
                R("Evaluation/backRedMoney",array($result,$wish,$redPrice));
                return;
            }
			if($result){
				if($param->returnJson){
					Output::instance()->object(['code'=>0,'msg'=>'ok']);
					return;
				}
				Output::instance()->object($result);
			}else{
				Output::instance()->resultCode(code_sql_error);
			}
		}
	}
	//ihziluoh 添加商品评价
	// 商品详情评论列表
	public static function getcommentList($pid,$start,$limit){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ProductCommentModel = M("module_product_comment");
		$relationMoel = M("module_comment_relation_product");
		Session::switchCustomer($customerId);
		$condition['_string']="a.pid=$pid or b.pid=$pid";
//		$condition['a.pid']=$pid;
		$condition['a.deleted']=0;
        $condition['a.type']=0;
		$condition['a.fromCustomerId']=$customerId;
		if(!isset($start)){$start = 0;}
		if(!isset($limit)){$limit = 10;}
		$result=$ProductCommentModel->alias('a')
				->join("wx_module_comment_relation_product b on a.pid=b.relationPid")
				->join("left join wx_".$customerId."_user_weixin_info user on a.fromUserName=user.openid")
				->join("inner join wx_module_product pro on a.pid = pro.id")
				->join('inner join wx_module_product_order_detail odetail on a.oid = odetail.oid')
				->join("wx_module_product_order_detail_specification spec ON spec.did=odetail.id")
				->where($condition)
				->field('a.*,user.headImgUrl,user.nickName,spec.firstSpecificName as sizeName, spec.secSpecificName as colorName,pro.name')
				->group("a.id")
				->order("a.createTime desc")
				->limit($start, $limit)
				->distinct(true)
				->select();
		foreach($result as $key=>$value){
			if($result[$key]["imgurl"]){
				$result[$key]["imgurl"]=explode(",",$value["imgurl"]);
			}
			$update = date("Y-m-d",strtotime($value["createTime"]));
			$datatime=date('Y-m-d');
			$yesterday = date("Y-m-d",time()-24*60*60);
			if($update==$datatime){
				$result[$key]["createTime"] = "今天 ".date("H:i",strtotime($value["createTime"]));
			}else if($update==$yesterday){
				$result[$key]["createTime"] = "昨天 ".date("H:i",strtotime($value["createTime"]));
			}else{
				$result[$key]["createTime"] = date("m-d H:i",strtotime($value["createTime"]));
			}
		}
		$count =$ProductCommentModel->alias("a")
				->join("wx_module_comment_relation_product b on a.pid=b.relationPid")
				->where($condition)
				->distinct(true)
				->order("a.createTime desc")
				->count();
		if($result){
			$out["list"]=$result;
		}else{
			$out["list"]=array();
		}
		$out["count"]=$count;
		$out["pageCount"]=0;
		$out["pageCount"]=getPageCount($count,$limit);
		Output::instance()->module("product","product_comment_list")->object($out);
	}

	/**
	 * [getObjectDetail 分享引导页获取商品详情]
	 * @param  [type] $id [description]
	 * @param  $shareArr /商品详情
	 * @return [type]     [description]
	 */
	public function getObjectDetail($param, $shareArr=null){
		$customerId = Session::$user["customerId"];
		$uid = Session::$user["userId"];
		Session::switchCustomer(0);
		$ProductModel = M("module_product");
		Session::switchCustomer($customerId);
		$platCustomerId = C('PLANT_CUSTOMERID');
		$id=$param->id;

		$result = $shareArr;
//		$fromGuid=$param->fromGuid;
//		if(!$fromGuid){
//			$fromGuid="";
//		}
		//$result=$ProductModel->field("id,fromCustomerId,tplId,name,title,recommend,description")->where("id=" . $id)->find();
//		if($param->fromUId){
//			$fromUId=$param->fromUId;
//		}
//		if($param->miUId){
//			$fromUId=$param->miUId;
//		}
		$p=new stdClass();
		$miUId=$param->miUId;;								//密友id
		$saleSourceUid=$param->saleSourceUid;			//销售源id
		$visitId= $param->visitId;							//上一次浏览id
//		if(!$param->lastShareUId){
			$param->lastShareUId = $uid;
//		}
		$lastShareUId= $param->lastShareUId;					//上一次分享人
		$p->miUId=$miUId;
		$p->saleSourceUd=$saleSourceUid;
		$p->qId=$param->qId;
		$p->visitId=$visitId;
		$p->lastShareUId=$lastShareUId;
		$formCustomerId=$result["fromCustomerId"];
		if($result) {
			if(!$param->toGuide) {
				$p->id=$id;
				$p=urlencode(json_encode($p));
				$detailUrl=C('SERVER_HOST') . "call.html?customerId={$formCustomerId}&module=product&method=getProduct&params=$p";
			} else {
				$p->id=$param->sId;
				$p=urlencode(json_encode($p));
				$detailUrl=C('SERVER_HOST') . "call.html?customerId={$platCustomerId}&module=quan&method=getGuideView&params=$p";
			}
			$result["detailUrl"]=$detailUrl;
			return $result;
		}
	}

	/**
	 * [setOrderStatus 更改订单状态]
	 * @param [type] $oid    [订单id]
	 * @param [type] $status [订单状态(只更改交易成功)]
	 */
	public function setOrderStatus($oid,$status = null, $expressNo = null, $expressName = null){
		if(empty($status)){
			$result = R('Product/myqupdateDividents',array($oid));
			if ($result) {
				Log::write("点击确认收货触发返现".$oid);
				R('Tuan/tuanBackMoney',array($oid));
				Output::instance()->object($result);
			} else {
				Output::instance()->resultCode(code_sql_error);
			}
		}else{
			$result = R('Product/updateOrderTipByOrderId',array($oid,'','',$status,
				$expressName, $expressNo));
		}
	}

	public function productExpress($oid,$name,$number){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$expressModel = M("module_express");
		$orderModel = M("module_product_order");
		Session::switchCustomer($customerId);
		$where['name']=array("eq",$name);
		$expressInfo = $expressModel->where($where)->find();
		if($expressInfo){
			$result = R($expressInfo['method'],array($expressInfo['name'],$expressInfo['value'],$number));
		}
		if(!$expressInfo||!$result){
			$result['name']="快递方式：".$name;
			$result['LogisticCode']="运 单 号：". $number;
		}
		$condition['a.id']=array("eq",$oid);
		$condition['c.deleted']=array("eq",0);
		$batchTrack = $orderModel->alias("a")
			->join("inner join wx_module_order_batch_delivery b on a.batchId=b.id")
			->join("inner join wx_module_order_batch_track c on c.batchId=b.id")
			->where($condition)
			->field("c.*")
			->order("c.createTime desc")
			->select();
		$result['batchTrack']=$batchTrack;
	    Output::instance()->module('product', 'product_express')->object($result);

	}
	public static function getCityByIp($ip){
		$ch = curl_init();
		$url = "http://apis.baidu.com/apistore/iplookupservice/iplookup?ip=".$ip;
		$header = array(
			'apikey: 1de79f0ef2b3aa846bd81dd322d48c6a'
		);
		curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// 执行HTTP请求
		curl_setopt($ch , CURLOPT_URL , $url);
		$res = curl_exec($ch);
		Log::write($res);
		$result = json_decode($res, true);
		if(!$result['retData']['city']||$result['retData']['city']=="None"){
			$result['retData']['city']="未知地区";
		}
		return $result['retData']['city'];
	}
	//优惠券更新到订单里
	public static function updateOrderCoupon($oid,$userCoponId){
		$customerId = Session::$user["customerId"];
		$userName = Session::$user['userName'];
		Session::switchCustomer(0);
		$orderModel = M("module_product_order");
		Session::switchCustomer($customerId);
		$orderModel->where("id=$oid")->setField("userCouponId",$userCoponId);
		Output::instance()->resultCode(code_success);
	}

	//优惠券列表
	public static function getCouponList($oid=null,$type=0,$start=0,$limit=10,$token=NULL,$isSelf=0,$cid=null){
		$token = Module::callModule("personCenter",null,"verifyToken",$token);
		$cid?$customerId=$cid:$customerId = Session::$user["customerId"];
		$userName = Session::$user['userName'];
		$userId = Session::$user['userId'];
		Session::switchCustomer(0);
		$userCoupon = M("module_user_coupon");
		$orderDetail = M("module_product_order_detail");
		$orderModel = M("module_product_order");
		Session::switchCustomer($customerId);
		$nowTime = date("Y-m-d H:i:s");
		switch($type){
			case 0:
				$where['a.status']=array("eq",0);
				$where['_string']="(b.isEffective=1 and b.endTime>'$nowTime') or b.isEffective=0";
				break;
			case 1:
				$where['a.status']=array(array("eq",1),array("eq",2),"or");
				break;
			case 2:
				$where['a.status']=array("eq",0);
				$where['_string']="b.isEffective=1 and b.endTime<'$nowTime' and b.startTime<'$nowTime'";
				break;
		}
		if($isSelf){
			$orderBy ="b.money desc";
		}else{
			$orderBy ="a.createTime desc";
		}
//		$where['a.openid']=array("eq",$userName);
		$where['a.userId']=array("eq",$userId);//LP修改
		$where['a.cId']=array("eq",$customerId);
		$couponList = $userCoupon->alias("a")
			->join("inner join wx_module_coupon b on a.couponId=b.id")
            ->join("wx_".$customerId."_user_weixin_info c on a.receiveUser=c.userId")
			->field("a.id as userCouponId,a.status,a.number,b.*,c.nickname")
			->where($where)
			->order($orderBy)
			->select();
        $where['a.status']=array(array("eq",1),array("eq",2),"or");
        $result['useredCount']=$userCoupon->alias("a")
            ->join("inner join wx_module_coupon b on a.couponId=b.id")
            ->where($where)
            ->count();
		$where['a.status']=array("eq",0);
		$where['_string']="b.isEffective=1 and b.endTime<'$nowTime' and b.startTime<'$nowTime'";
		$result['overdue']=$userCoupon->alias("a")
			->join("inner join wx_module_coupon b on a.couponId=b.id")
			->where($where)
			->count();
		$where['a.status']=array("eq",0);
		$where['_string']="(b.isEffective=1 and b.endTime>'$nowTime') or b.isEffective=0";
		$result['canuserCount']=$userCoupon->alias("a")
			->join("inner join wx_module_coupon b on a.couponId=b.id")
			->where($where)
			->count();
		foreach($couponList as $key=>$value){
			$couponList[$key]['startTime'] = date("Y/m/d",strtotime($value['startTime']));
			$couponList[$key]['endTime'] = date("Y/m/d",strtotime($value['endTime']));
		}
		$canUserList=array();
		$notCanUserList=array();
		if($type==0&&$oid){
			$tagList = $orderDetail->alias("a")
				->join("inner join wx_module_product_tag_list b on a.pid=b.pid")
				->where("a.oid=$oid")
				->field("b.tagId")
				->group("b.tagId")
				->select();
			$orderInfo = $orderModel->where("id=$oid")->find();
			foreach($couponList as $key=>$value){
				if($value['accOrderPrice']!=1&&$value['accProductTags']!=1){
					break;
				}
				$couponList[$key]['canUse']=0;
				if($value['accOrderPrice']==1){
					if($orderInfo['price']>=$value['minPrice']){
						$reduction=true;
					}else{
						$reduction=false;
					}
				}else{
					$reduction=true;
				}
				if($value['accProductTags']==1){
					$proTagList = explode(",",$value['productTags']);
					$satisfy=false;
					foreach($tagList as $tag){

						if(in_array($tag['tagId'],$proTagList)){
							$satisfy = true;
							break;
						}
					}
				}else{
					$satisfy=true;
				}
				if($satisfy&&$reduction){
					$couponList[$key]['canUse']=1;
					array_push($canUserList,$couponList[$key]);
					continue;
				}
//				$notCanUserList[]=$couponList[$key];
				array_push($notCanUserList,$couponList[$key]);
			}
			$couponList = array_merge($canUserList,$notCanUserList);
		}

		$result['type']=$type;
		$result['couponList']=$couponList;
		$result['mallHue']=self::getMallHue();
		if($oid){
			if($isSelf){
				return $canUserList;
			}
			Output::instance()->module("product","product_coupon_list")->object($result);
		}else{
			Output::instance()->module("product","product_coupon_mylist")->object($result);
		}

	}
	//优惠券首页
	public static function couponIndex($sendId){
		$customerId = Session::$user["customerId"];
		$userName = Session::$user['userName'];
		Session::switchCustomer(0);
		$couponSend = M("module_coupon_send");
		Session::switchCustomer($customerId);
		$result = $couponSend->alias("a")
			->join("inner join wx_module_coupon_scheme b on a.schemeId=b.id")
			->join("wx_".$customerId."_user_weixin_info c on a.openid=c.openid")
			->field("a.id,a.copiesPrice,a.surplusPrice,a.copiesNum,a.surplusNum,b.config,b.shareTitle,b.shareImg,b.shareDescribe,c.headimgurl")
			->where("a.id=$sendId")
			->find();
		if($result['config']){
			$result['config']=json_decode($result['config'],true);
		}
		Output::instance()->module("product","product_coupon_index")->object($result);
	}
	//领取优惠券
	public static function receiveCoupon($sendId,$token){
		$token = Module::callModule("personCenter",null,"verifyToken",$token);
		$customerId = Session::$user["customerId"];
		$userName = Session::$user['userName'];
		$userId = Session::$user['userId'];
		Session::switchCustomer(0);
		$couponSend = M("module_coupon_send");
		$sendDetail =M("module_coupon_send_detail");
		$userCoupon = M("module_user_coupon");
		$miyouquan = M("miyouquan");
		$malluser = M("mimall_user");
		Session::switchCustomer($customerId);
		$mallstore = M("module_mall_store");
		$userModel = M("user_weixin_info");
//		$selfCondition['openid']=array("eq",$userName);
		$selfCondition['userId']=array("eq",$userId);//LP修改
		$selfCondition['sendId']=array("eq",$sendId);
		$selfCondition['cId']=array("eq",$customerId);
		$schemeInfo=$couponSend->alias("a")
			->join("inner join wx_module_coupon_scheme b on a.schemeId=b.id")
			->join("wx_".$customerId."_user_weixin_info c on a.openid=c.openid")
			->field("a.id as sendId,c.nickname,c.headimgurl,b.id,b.config,b.shareTitle,b.shareImg,b.shareDescribe,b.receiveType")
			->where("a.id=$sendId")
			->find();
		$selfInfo = $userModel->where("openid ='$userName'")->field("nickname,headimgurl")->find();
		if($schemeInfo['config']){
			$schemeInfo['config'] = str_replace('{{name}}',$selfInfo['nickname'],$schemeInfo['config']);
			$schemeInfo['config'] = json_decode($schemeInfo['config'],true);
			if(!$schemeInfo['config']['mallUrl']){
				$mallInfo = $mallstore->find();
				$schemeInfo['config']['mallUrl'] = $mallInfo['storeurl'];
			}
		}
		$receiveResult = $userCoupon->alias("a")
			->join("inner join wx_module_coupon b on a.couponId=b.id")
			->field("b.*")
			->where($selfCondition)->select();
		$result['received']=1;
		if(!$receiveResult){
			$result['received']=0;
			$couponList = $sendDetail->alias("a")
				->join("inner join wx_module_coupon b on a.couponId=b.id")
				->field("a.*,b.money")
				->where("a.sendId=$sendId and a.surplusNum>0")->select();
			if($schemeInfo['receiveType']){
				if($couponList&&($userName || $userId)){	//LP修改
					foreach($couponList as $key=>$value){
						$data['openid']=$userName;
						$data['cId']=$customerId;
						$data['schemeId']=$schemeInfo['id'];
						$data['couponId']=$value['couponId'];
						$data['sendDetailId']=$value['id'];
						$data['number']=1;
						$data['createTime']=date("Y-m-d H:i:s");
						$data['sendId']=$sendId;
						$data['userId']=$userId;		//LP修改
						$userCouponId = $userCoupon->add($data);
						if($userCouponId){
							$sql = 'update wx_module_coupon_send_detail set surplusNum=surplusNum-1 where id='.$value['id'];
							$sendDetail->query($sql);
							$sql = 'update wx_module_coupon_send set surplusNum=surplusNum-1,surplusPrice=surplusPrice-'.$value['money'].' where id='.$value['sendId'];
							$sendDetail->query($sql);
						}
					}
					$receiveResult = $userCoupon->alias("a")
						->join("inner join wx_module_coupon b on a.couponId=b.id")
						->field("b.*")
						->where($selfCondition)->select();
				}
			}else{
				$randIndex = rand(0,count($couponList)-1);
				if($couponList[$randIndex]&&($userId ||$userName )){//LP修改
					$data['openid']=$userName;
					$data['cId']=$customerId;
					$data['schemeId']=$schemeInfo['id'];
					$data['couponId']=$couponList[$randIndex]['couponId'];
					$data['sendDetailId']=$couponList[$randIndex]['id'];
					$data['number']=1;
					$data['createTime']=date("Y-m-d H:i:s");
					$data['sendId']=$sendId;
					$data['userId']=$userId;				//LP修改
					$userCouponId = $userCoupon->add($data);
					if($userCouponId){
						$sql = 'update wx_module_coupon_send_detail set surplusNum=surplusNum-1 where id='.$couponList[$randIndex]['id'];
						$sendDetail->query($sql);
						$sql = 'update wx_module_coupon_send set surplusNum=surplusNum-1,surplusPrice=surplusPrice-'.$couponList[$randIndex]['money'].' where id='.$couponList[$randIndex]['sendId'];
						$sendDetail->query($sql);
					}
					$receiveResult = $userCoupon->alias("a")
						->join("inner join wx_module_coupon b on a.couponId=b.id")
						->field("b.*")
						->where($selfCondition)->select();
				}
			}

		}
		//领取列表
		$receiveList=$userCoupon->alias("a")
			->join("inner join wx_module_coupon c on a.couponId=c.id")
			->join("wx_".$customerId."_user_weixin_info b on a.openid=b.openid")
			->where("a.sendId=$sendId")
			->field("b.nickname,b.headimgurl,c.money,a.createTime")
			->order("a.createTime desc")
			->select();
		$nowTime = time();
		foreach($receiveList as $key=>$value){
			$time = $nowTime-strtotime($value['createTime']);
			$createTime = floor($time/(24*3600));
			$receiveList[$key]['createTime']=$createTime."天前";
			if(!$createTime){
				$createTime = floor($time/(3600));
				$receiveList[$key]['createTime']=$createTime."小时前";
			}
			if(!$createTime){
				$createTime = floor($time/(60));
				$receiveList[$key]['createTime']=$createTime."分钟前";
			}
		}
		foreach($receiveResult as $key=>$value){
			$receiveResult[$key]['startTime'] = date("Y/m/d",strtotime($value['startTime']));
			$receiveResult[$key]['endTime'] = date("Y/m/d",strtotime($value['endTime']));
		}
		$result['receiveList']=$receiveList;
		$result['schemeInfo']=$schemeInfo;
		$result['selfReceive']=$receiveResult;
		$result['selfInfo']=$selfInfo;
		$result['mallHue']=self::getMallHue();
		Output::instance()->module("product","product_coupon_detail")->object($result);
	}
	public function toSearch(){
		$customerId = Session::$user["customerId"];
		$userName = Session::$user['userName'];
		Session::switchCustomer(0);
		$userHistory = M("mall_user_search_history");
		$searchHistory = M("mall_search_history");
		Session::switchCustomer($customerId);
		$userWhere['cId']=array("eq",$customerId);
		$userWhere['openid']=array("eq",$userName);
		$userWhere['deleted']=array("eq",0);
		$userHistoryList = $userHistory
			->where($userWhere)
			->order("createTime desc")
			->field("searchHistory")
			->select();
		$searchWhere['cId']=array("eq",$customerId);
		$searchHistoryList = $searchHistory
			->where($searchWhere)
			->field("searchHistory")
			->order("count desc")
			->limit(0,20)
			->select();
		$result['userHistoryList']=$userHistoryList;
		$result['searchHistoryList']=$searchHistoryList;
		Output::instance()->module("product","product_mall_search")->object($result);
	}
	//删除历史记录
	public function delSearchHistory(){
		$customerId = Session::$user["customerId"];
		$userName = Session::$user['userName'];
		Session::switchCustomer(0);
		$userHistory = M("mall_user_search_history");
		Session::switchCustomer($customerId);
		$userWhere['cId']=array("eq",$customerId);
		$userWhere['openid']=array("eq",$userName);
		$userWhere['deleted']=array("eq",0);
		$result = $userHistory->where($userWhere)->setField("deleted",1);
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(1,"删除失败！");
		}
	}
	public function searchProduct($keyword,$qId=null,$miUId=null){
		$customerId = Session::$user["customerId"];
		$userName = Session::$user['userName'];
		Session::switchCustomer($customerId);
		$mallInfoModel = M("module_mall_store");
		$mallInfo = $mallInfoModel->find();
		$Guid = new Guid();
		$guid = $Guid->toString();
		$result['guid']=$guid;
		$reuslt['mallInfo']=$mallInfo;
		$result['keyword']=$keyword;
		$result['mallHue']=self::getMallHue();
		Output::instance()->module("product","product_mall_searchresult")->object($result);
	}
	public function searchResults($keyword,$start=0,$limit=20){
		$customerId = Session::$user["customerId"];
		$userName = Session::$user['userName'];
		Session::switchCustomer(0);
		$productModel = M("module_product");
		$userHistory = M("mall_user_search_history");
		$searchHistory = M("mall_search_history");

		$periodModel = M("module_mill_period");
		Session::switchCustomer($customerId);
		if($keyword){
			$userWhere['cId']=array("eq",$customerId);
			$userWhere['openid']=array("eq",$userName);
			$userWhere['deleted']=array("eq",0);
			$userWhere['searchHistory']=array("eq",$keyword);
			$userHistoryResult = $userHistory
				->where($userWhere)
				->find();
			if(!$userHistoryResult){
				$data['cId']=$customerId;
				$data['openid']=$userName;
				$data['searchHistory']=$keyword;
				$data['createTime']=date("Y-m-d H:i:s");
				$userHistory->add($data);
			}
			$searchWhere['cId']=array("eq",$customerId);
			$searchWhere['searchHistory']=array("eq",$keyword);
			$searchHistoryResult =  $searchHistory
				->where($searchWhere)
				->find();
			if(!$searchHistoryResult){
				$data['cId']=$customerId;
				$data['searchHistory']=$keyword;
				$data['count']=0;
				$data['createTime']=date("Y-m-d H:i:s");
				$data['updateTime']=date("Y-m-d H:i:s");
				$searchHistory->add($data);
			}else{
				$data['count']=$searchHistoryResult['count']+1;
				$data['updateTime']=date("Y-m-d H:i:s");
				$searchHistory->where("id=".$searchHistoryResult['id'])->save($data);
			}
		}
		$where['a.fromCustomerId']=array("eq",$customerId);
		$where['a.isRemoved']=array("eq",0);
		$where["a.deleted"]=array("eq",0);
		$where['_string']="a.name like '%$keyword%' or c.name like '%$keyword%'";
		$ids = $productModel->alias("a")
            ->join("wx_module_product_tag_list b on a.id=b.pid")
            ->join("wx_module_product_tag c on b.tagId=c.id")
            ->where($where)->field("group_concat(a.id) as ids")->find();
		$ids = $ids['ids'];
		$productList = $productModel->alias("a")
			->join("wx_module_product_tag_list b on a.id=b.pid")
			->join("wx_module_product_tag c on b.tagId=c.id")
			->join("wx_module_product_specification spe on a.id=spe.pid")
			->field("a.*,MIN(spe.discountedPrice) as minDisPrice,MAX(spe.discountedPrice) as maxDisPrice,
				MIN(spe.miPrice) as minMiPrice,MAX(spe.miPrice) as maxMiPrice,MAX(spe.fixedPrice) as maxFixedPrice,MIN(spe.fixedPrice) as minFixedPrice")
			->where("a.id in ($ids)")
			->limit($start,$limit)
			->order("a.createTime desc")
			->group("a.id")
			->select();
		foreach($productList as $key => $value){
			if($value['isChainPro']){
				$supProductInfo = $productModel->where("id=".$value['supplyProId'])->find();
				$productList[$key]['inventoryCount']=$supProductInfo['inventoryCount'];
				$productList[$key]['inventory']=$supProductInfo['inventory'];
			}
			$picUrl1 = json_decode($value["picUrl1"],true);
			if($picUrl1[1]&&$picUrl1[1]['picUrl']){
				$productList[$key]['picUrl']=$picUrl1[1]['picUrl'];
			}
			$json = json_decode($value["json"],true);
			$jsonName = array_keys($json);
			foreach($jsonName as $k=>$val){
				$productList[$key][$val]=$json[$val];
				$value[$val]=$json[$val];
			}
			$seckillStartTime = strtotime($json["seckillStartTime"]);
			$seckillEndtime = strtotime($json["seckillEndTime"]);
			$newTime = time();
			if($newTime>=$seckillStartTime){
				$productList[$key]["seckillIsStart"]=1;
			}else{
				$productList[$key]["seckillIsStart"]=0;
			}
			if($newTime>$seckillEndtime){
				$productList[$key]["seckillIsEnd"]=1;
			}else{
				$productList[$key]["seckillIsEnd"]=0;
			}
			$productList[$key]["nowTime"] = date("Y-m-d H:i:s");
			unset($productList[$key]["json"]);
			if($value["playType"]=="3"){
				$periodInfo = $periodModel->where("pid=".$value["id"])->field("beenSold,periodState")->order("id desc")->find();
				if(!$periodInfo["beenSold"]){
					$periodInfo["beenSold"]=0;
				}
				$productList[$key]["beenSold"] = $value["totalCopies"]-$periodInfo["beenSold"];
				$productList[$key]["periodState"] = $periodInfo["periodState"];
				$productList[$key]["barProgress"] = floor($periodInfo["beenSold"]/$value["totalCopies"]*100)."%";
			}else if($value["playType"]=="6") {
				$value['supportSum']?"":$value['supportSum']=0;
				$productList[$key]['day']=ceil((strtotime($value['crowEndtime'])-time())/(24*60*60));
				$productList[$key]["barProgress"] = ceil($value["supportSum"]/$value["crowTarget"]*100)."%";
			}
			$value["picTag"]?$productList[$key]["picTag"] = explode(",",$value["picTag"]):'';
			$value["priceTag"]?$productList[$key]["priceTag"] = explode(",",$value["priceTag"]):'';
		}
		$param = new stdClass();
		$param->qId = $qId;
		$param->miUId = $miUId;
		if(self::isEnjoyMiPrice($param)){
			$result['isEnjoyMiPrice']=1;
		}else{
			$result['isEnjoyMiPrice']=0;
		}
		$result['keyword']=$keyword;
		$result['productList']=$productList;
		Output::instance()->object($result);
	}

	/**
	 * 创建/更新用户收货地址
	 * @param string $addressid 地址id
	 * @param $orderType  是否是活动id
	 * @param $userName
	 * @param $fullName
	 * @param $phone
	 * @param $province
	 * @param $city
	 * @param $country
	 * @param $address
	 * @param $postcode
	 */

	public function createUserAddress($addressid,$isActivity, $fullName, $phone, $province, $city, $country, $address, $postcode){
		$customerId = Session::$user["customerId"];
		$userName = Session::$user["userName"];
		$userId = Session::$user["userId"];
		$UserAddress = M('user_receiver_address');
		$UserInfo = M('user_info');

		$isDefault = get_User_Address_fromUserName($userId,$isActivity);				//LP修改
		if($isDefault){
			foreach ($isDefault as $key => $val) {
				$UserAddress->where(['id' => $val['id']])->save(['isDefault' => 0]);
			}
		}
		//判断是否有地址id有更新 没有新增
		if(!$addressid){
			if ($isActivity==1) {
				$data["isAcitivity"] = 1;
			}else{
				$data["province"] = $province;
				$data["city"] = $city;
				$data["country"] = $country;
				$data["address"] = $address;
				$data["postcode"] = $postcode;
				$data["isAcitivity"] = 0;
			}
			$data["userName"] = $userName;
			$data["receiverName"] = $fullName;
			$data["phone"] = $phone;
			$data["isDefault"] = 1;
			$data["createTime"] = date('Y-m-d H:i:s',time());
			$data["uid"] = $userId;
			$result = $UserAddress->add($data);
			$userinfo = $UserInfo->where(['uid'=>$userId])->find();									//LP修改
			if($userinfo){
				$update = $UserInfo->where(['uid'=>$userId])->save(["lastAddressId"=>$result]);//LP修改
			}else{
				$userdata['fromUserName'] = $userName;
				$userdata['fullName'] = $fullName;
				$userdata['phone'] = $phone;
				$userdata['address'] = $province.' '.$city.' '.$country.' '.$address;
				$userdata['lastAddressId'] = $result;
				$userdata['uid'] = $userId;															//LP修改
				$userinfocreate = $UserInfo->add($userdata);
			}


		}else{
			if ($isActivity==1) {
				$data["isAcitivity"] = 1;
			}else{
				$data["province"] = $province;
				$data["city"] = $city;
				$data["country"] = $country;
				$data["address"] = $address;
				$data["postcode"] = $postcode;
				$data["isAcitivity"] = 0;
			}
			$data["userName"] = $userName;
			$data["receiverName"] = $fullName;
			$data["phone"] = $phone;
			$data["isDefault"] = 1;
			$data["createTime"] = date('Y-m-d H:i:s',time());
			$result = $UserAddress->where(['id'=>$addressid])->save($data);
			$update = $UserInfo->where(['uid'=>$userId])->save(["lastAddressId"=>$addressid]);	//LP修改
		}
		if($result){
			Output::instance()->object($result);
		}else{
			Output::instance()->resultCode(code_sql_error);
		}


	}

	/**
	 * 获取用户下所有地址列表
	 * @param $lastAddressId user_info表里是否有值
	 * @param $orderType 类型是否等于6
	 */
	public function getAddressList($isActivity){
		$customerId = Session::$user["customerId"];
		$userId = Session::$user["userId"];
		$UserAddress = M('user_receiver_address');
		$UserInfo = M('user_info');
		$userName = Session::$user["userName"];
		$userInfo = get_UserInfo_by_fromUserName($userId);//LP修改
		//如果user_info中没有$lastAddressId,将user_info中的数据追加到address表里
		if(!$userInfo['lastAddressId']){
			if($userInfo){
				$data["userName"] = $userName;
				$data["uid"] = $userId;
				$data["receiverName"] = $userInfo['fullName'];
				$data["phone"] = $userInfo['phone'];
				$data["address"] = $userInfo['address'];
				$data["isDefault"] = 1;
				if($isActivity==1){
					$data["isAcitivity"] = 1;
				}
				$result = $UserAddress->add($data);
				$update = $UserInfo->where(['uid'=>$userId])->save(["lastAddressId"=>$result]);

			}
		}
		//如果$orderType==6输出活动信息 否则输出地址列表
		if($isActivity==1){
			$result = $UserAddress->where(["uid"=>$userId,"deleted"=>0,"isAcitivity"=>1])->select();
		}else{
			$result = $UserAddress->where(["uid"=>$userId,"deleted"=>0,"isAcitivity"=>0])->select();
		}
		output::instance()->objArray($result);
	}

	/**
	 * 编辑用户收货地址
	 * @param $id
	 */
	public function editUserAddress($id){

		$customerId = Session::$user["customerId"];
		$UserAddress = M('user_receiver_address');
		$result = $UserAddress->where(["id"=>$id])->find();
		output::instance()->object($result);

	}
    //y优惠券详情
    public function couponInfo($id){
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $userCoupon=M("module_user_coupon");
        Session::switchCustomer($customerId);
        $mallModel = M("module_mall_store");
        $result['mallInfo'] = $mallModel->field("name,logo")->find();
        $result['couponInfo'] = $userCoupon->alias("a")
            ->join("inner join wx_module_coupon b on a.couponId=b.id")
            ->join("wx_".$customerId."_user_weixin_info c on a.openid=c.openid")
            ->where("a.id=$id")
            ->field("a.id,a.openid,c.nickname,a.status,b.name,b.money,b.isEffective,b.startTime,b.endTime,b.recommend")
            ->find();
        $result['couponInfo']['startTime']=date("Y.m.d",strtotime($result['couponInfo']['startTime']));
        $result['couponInfo']['endTime']=date("Y.m.d",strtotime($result['couponInfo']['endTime']));
        $result['quanInfo']=self::isPartner();
        Output::instance()->module("product","product_coupon_info")->object($result);

    }
    //领取分享的优惠券
    public function receiveShareCoupon($id){
        $userName = Session::$user['userName'];
        $userId = Session::$user['userId'];
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $userCoupon=M("module_user_coupon");
        Session::switchCustomer($customerId);
        $couponInfo = $userCoupon->where("id=$id")->find();
        if($couponInfo['status']==1){
            Output::instance()->resultCode(1,"该优惠券已使用!");
            return;
        }
        if($couponInfo['status']==2){
            Output::instance()->resultCode(1,"该优惠券已被领取!");
            return;
        }
        $userCoupon->where("id=$id")->setField(["status"=>2,"receiveUser"=>$userId]);
        $couponInfo['sourceCoupon']=$couponInfo["id"];
        unset($couponInfo["id"]);
        $couponInfo['openid']=$userName;
		$couponInfo['userId']= $userId;
        $userCoupon->add($couponInfo);
        Output::instance()->resultCode();
    }

	/**
	 * 用户地址删除
	 * @param $id
	 */
	public function deleteUserAddress($id){
		$customerId = Session::$user["customerId"];
		$UserAddress = M('user_receiver_address');
		$result = $UserAddress->where(["id"=>$id])->save(['deleted'=>1]);
		output::instance()->object($result);

	}

	/**
	 * 设置默认地址
	 * @param $id
	 * @param $isActivity
	 */
	public function setDefaultAddress($id,$isActivity){
		$customerId = Session::$user["customerId"];
		$userId = Session::$user["userId"];
		$UserAddress = M('user_receiver_address');
		$UserInfo = M('user_info');
		$userName = Session::$user["userName"];
		$isDefault = get_User_Address_fromUserName($userId,$isActivity);
		if($isDefault){
			foreach ($isDefault as $key => $val) {
				$UserAddress->where(['id' => $val['id']])->save(['isDefault' => 0]);
			}
		}
		$result = $UserAddress->where(["id"=>$id])->save(['isDefault'=>1]);
		$update = $UserInfo->where(['fromUserName'=>$userName])->save(["lastAddressId"=>$id]);
		Output::instance()->resultCode();

	}
	//微信浏览器选择支付宝支付的过渡页
	public function orderBrowserOpen($id){
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$orderModel = M("module_product_order");
		Session::switchCustomer($cid);
		if(!isMicroMessengerUserAgent()){
			$orderInfo = $orderModel->alias("a")
				->join("inner join wx_module_product_order_detail b on a.id=b.oid")
				->where("a.id in ($id)")->field("group_concat(b.name) as name,tempSerialNumber")->find();
				$desc = $orderInfo['name'];
                $sn = $orderInfo['tempSerialNumber'];
				$orderInfo = $orderModel->field("sum(price) as price,sum(couponMoney) as couponMoney,sum(purseMoney) as purseMoney,sum(logisticsCost) as logisticsCost")
				->where("id in ($id)")->find();
			$totalFee = $orderInfo['price']+$orderInfo['logisticsCost'];
			if($orderInfo['couponMoney']){
				$totalFee-=$orderInfo['couponMoney'];
			}
            if($orderInfo['purseMoney']){
                $totalFee-=$orderInfo['purseMoney'];
            }
			$url =  C('SERVER_HOST')."Alipay/submitPay.json?cid=$cid&sn=$sn&desc=$desc&totalFee=$totalFee";
			redirect($url);
			return;
		}
		$result['id']=$id;
		Output::instance()->module("product","product_browser_open")->object($result);
	}
	//判断订单是否满足晒单要求
    public static function commentRequire($oid){
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        $orderDetailModel = M("module_product_order_detail");
        $commentConfig = M("module_comment_config");
        Session::switchCustomer($cid);
        $configInfo = $commentConfig->where("customerId=$cid")->find();
//        $orderInfo = $orderModel->where("id=$oid")->field("status,completionTime")->find();
//        $completionTime = strtotime($orderInfo['completionTime']);
//        $day = $configInfo['validityDays'];
//        $now = date("Y-m-d H:i:s");
//        $now = strtotime("$now -$day day");
//        if($orderInfo['status']!=order_status_ok||$now>$completionTime){
//            return false;
//        }
        $productList = $orderDetailModel
            ->where("oid=$oid")
            ->field("price,count,pid")
            ->group("pid")
            ->select();
        foreach($productList as $key=>$value){
            $productList[$key]['redMoney']=false;
            if($value['price']*$value['count']>=$configInfo['singleProductAmount']){
                return true;
            }
        }
        return false;
    }

	/**
	 * 表单订单提交
	 * @param null $miUid	/从社群分享出人的miuid
	 * @param null $qId		/营销圈id
	 * @param null $sId		/保存内容时wx_mishare产生的分享id
	 * @param null $visitId	/上次的分享id
	 * @param null $formId	/表单id
	 * @param null $contentId	/内容id
	 * @param null $customizedInfo	/表单提交的信息
	 * @param null $module	/模块
	 * @param null $moduleId	/moduleId实际和内容id相同
	 */
	public static function preSubmitFormOrder($miUid=null, $qId=null, $sId=null ,$visitId=null, $formId,
									   $customizedInfo=null,$module,$moduleId){
		Log::write('jie----333-'.$formId);
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user['customerId'];
		$userName = Session::$user['userName'];
		$uId = Session::$user['userId'];
		Session::switchCustomer(0);
		$MallUserModel=M("mimall_user");
		$quan_tab = M('miyouquan');
		$quanUser_tab = M('quan_user');
		$form_tab = M('form');
		$agentModel = M("vendor_agent");
		$order_tab = M('module_product_order');
		$orderDetail_tab = M('module_product_order_detail');
		Session::switchCustomer($cid);

		//获取推荐人信息
		$saleSource = '';
		if(!$miUid || !$qId){ //如果购买参数不带密友相关信息，从之前的购买关系表中查找
			$miUser=$MallUserModel->where("openid='".$userName."' and cId=".$cid)->find();
			$miUserInfo = $quanUser_tab->where(['uid'=>$miUser['miUid'], 'qid'=>$miUser['qId'], 'deleted'=>0,'status'=>1])->find();
			Log::write("取锁定用户表信息   ".$MallUserModel->getLastSql()."--".$miUser["miUid"]);
			if($miUserInfo){
				if($miUser && count($miUser) > 0){
					$miUid=$miUser["miUid"];
					$qId=$miUser["qId"];
					$saleSource=$miUser["saleSource"];
				}
			}
		}
		//获取二级推荐人信息
		$refereeInfo = null;
		if($miUid&&$qId){
			$refereeInfo = $quanUser_tab->alias("a")
				->join("wx_quan_user b on a.refereeUid = b.uid")
				->where("a.qid = $qId and a.uid=$miUid and a.qid = b.qid and b.status=1 and b.deleted=0")
				->field("a.refereeUid,b.refereeUid as parentRefereeUid,a.saleSource")
				->find();
			$saleSource = $refereeInfo['saleSource'];
		}

		//获取圈子详情
		$quanInfo=$quan_tab->where(['id'=>$qId])->find();
		//获取表单详情
		$formInfo = $form_tab->where(['id'=>$formId, 'cid'=>$cid, 'status'=>0])->field('formName, type as isPay, vendorId,
		payPrice, supplyPrice, platCut, saleCut')->find();

		if($formInfo == null){
			Output::instance()->object([
				'code'=>1,
				'msg'=>'此表单已停用,暂无法提交',
				'results'=>[]
			]);
			return;
		}
		//从提交的信息中获取fullname和phone
		$fullName = $phone = $address = $province = $city = '';
		if($customizedInfo){
			$formValArr = json_decode(json_encode($customizedInfo),true);
			foreach($formValArr as $k=>$v){
				switch($v['type']){
					case'name':
						$fullName = $v['value'];
						break;
					case 'phone':
						$phone = $v['value'];
						break;
					case 'city':
						$province = $v['value']['provice'];
						$city = $v['value']['city'];
						//$county = $v['value']['county'];
						break;
					case 'address':
						$address = $v['value'];
						break;
					default:
						break;
				}
			}
		}
		$data = [];
		$data['fromCustomerId'] = $cid;
		$data['qId'] = $qId;
		$data['uId'] = $uId;
		$data['miUid'] = $miUid;
		$data['refereeUid'] = $refereeInfo['refereeUid'];
		$data['parentRefereeUid'] = $refereeInfo['parentRefereeUid'];
		$data['saleSource'] = $saleSource;
		$data['vId'] = $formInfo['vendorId'];
		$data['miAward'] = $quanInfo['miAward'];
		$data['lordAward'] = $quanInfo['lordAward'];
		$data['fromUserName'] = $userName;
		$data['deliveryType'] = 'delivery';
		$data['fullName'] = $fullName?$fullName:'';
		$data['phone'] = $phone?$phone:'';
		$data['address'] = $address?$address:'';
		$data['module'] = $module;
		$data['moduleId'] = $moduleId;
		$data['createTime'] = date('Y-m-d H:i:s');
		$data['updateTime'] = date('Y-m-d H:i:s');
		$data['province'] = $province?$province:'';
		$data['city'] = $city?$city:'';
		$data['type'] = 'form';
		$data['orderType'] = 9;	//之前订单类型定义到8,shiyong常量
		if($formInfo['isPay'] == 1){
			$data['status'] = 'paying';
			$data['price'] = $formInfo['payPrice'];
		}else{
			$data['status'] = 'submission';
			$data['price'] = 0;
		}

		M()->startTrans();
		$oid = $order_tab->add($data);
		if(!$oid){
			M()->rollback();
			Output::instance()->object([
				'code'=>1,
				'msg'=>'订单保存失败',
				'results'=>[]
			]);
			return;
		}
		//保存订单详情
		$dataDetail = [];
		$dataDetail['fromUserName'] = $userName;
		$dataDetail['sId'] = $sId;
		$dataDetail['visitId'] = $visitId;
		$dataDetail['qId'] = $qId;
		$dataDetail['miUid'] = $miUid;
		$dataDetail['saleCut'] = $formInfo['saleCut']?$formInfo['saleCut']:0;
		$dataDetail['platCut'] = $formInfo['platCut']?$formInfo['platCut']:0;
		$lordAward = 1;
		if($qId && $miUid){	//推荐人分成
			$dataDetail['miUserRatio'] = $quanInfo['miAward'];
			$dataDetail['isMiUserCut'] = $formInfo['payPrice'] * $quanInfo['miAward'];
			$lordAward-=$quanInfo['miAward'];
		}

		if($qId && $refereeInfo['refereeUid']){//二级推荐人分成
			$dataDetail['refereeAward'] = $quanInfo['refereeAward'];
			$dataDetail['isRefereeCut'] = $formInfo['payPrice'] * $quanInfo['refereeAward'];
			$lordAward-=$quanInfo['refereeAward'];
		}

		if($qId && $refereeInfo['parentRefereeUid']){//三级推荐人分成
			$dataDetail['parentRefereeAward'] = $quanInfo['parentRefereeAward'];
			$dataDetail['isParentRefereeCut'] = $formInfo['payPrice'] * $quanInfo['parentRefereeAward'];
			$lordAward-=$quanInfo['parentRefereeAward'];
		}

		if($qId && $miUid){//主公分成
			$dataDetail['lordRatio'] = $lordAward;
			$dataDetail['isLordCut'] = $formInfo['payPrice'] * $lordAward;
		}

		$agentInfo = $agentModel->where("find_in_set(".$formInfo['vendorId'].",vendors)")->find();
		if($agentInfo !== null){
			$agentAward = $agentInfo['agentAward'];
			$dataDetail['platRatio'] = 1-$agentAward;		//平台佣金比例
			$dataDetail['agentRatio'] = $agentAward;		//代理商佣金比例
			$dataDetail['isAgentCut'] = ($formInfo['platCut']?$formInfo['platCut']:0)*$agentAward;		//代理商佣金
			$dataDetail['isPlatCut'] = ($formInfo['platCut']?$formInfo['platCut']:0)*$dataDetail['platRatio'];//平台佣金
		}
		$dataDetail['isVendorCut'] = $formInfo['supplyPrice']?$formInfo['supplyPrice']:0;

		$dataDetail['oid'] = $oid;
		$dataDetail['pid'] = $formId;
		$dataDetail['name'] = $formInfo['formName'];
		$dataDetail['contentId'] = $moduleId;
		$dataDetail['fixedPrice'] = $formInfo['payPrice'];
		$dataDetail['type'] = 'buy';
		$dataDetail['price'] = $formInfo['payPrice'];
		$dataDetail['count'] = 1;
		$dataDetail['userId'] = $uId;
		$dataDetail['customizedInfo'] = json_encode($customizedInfo, JSON_UNESCAPED_UNICODE);

		$bool = $orderDetail_tab->add($dataDetail);
		if(!$bool){
			M()->rollback();
			Output::instance()->object([
				'code'=>1,
				'msg'=>'订单提交失败',
				'results'=>[]
			]);
			return;
		}
		M()->commit();
		Output::instance()->object([
			'code'=>0,
			'msg'=>'提交成功',
			'oid'=>$oid
		]);
	}

	/**
	 * 表单订单支付
	 * @param $orderId /订单id
	 * @param $payType /支付方式
	 */
	public function formOrderPay($orderId,$payType=null){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$userName = Session::$user['userName'];
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$form_tab = M('form');
		$order_tab = M('module_product_order');
		$vendorModel = M("mivendor");
		//$orderDetail_tab = M('module_product_order_detail');
		Session::switchCustomer($cid);
		$TemplateModel = M("template_messages");
		//判断是否需要调用支付
		$orderInfo = $order_tab->alias('a')
			->join('inner join wx_module_product_order_detail b on a.id=b.oid')
			->join('wx_'.$cid.'_user c on a.uid=c.id')
			->field('a.*, b.pid, b.fixedPrice,c.userName,c.phone as userPhone')
			->where(['a.id'=>$orderId])
			->find();
		//var_dump($order_tab->getLastSql());exit;
		if(!$orderInfo){
			Output::instance()->object([
				'code'=>1,
				'msg'=>'异常提交',
				'results'=>[]
			]);
			return;
		}
		$payPrice = $form_tab->where(['cId'=>$cid, 'id'=>$orderInfo['pid']])->field('payPrice, type')->find();
		if($payPrice['type'] == 2){
			//此时不需要支付
			$data['serialNumber'] = $data['tempSerialNumber'] = self::createOrderSerialNumber($orderId, $cid);
			if(empty($data['serialNumber']) || empty($data['tempSerialNumber'])){
				Log::write('更新订单状态失败orderId:'.$orderId.'|cid:'.$cid);
				Output::instance()->object([
					'code'=>1,
					'msg'=>'提交失败',
					'results'=>[]
				]);
				return;
			}
			$data['updateTime'] = date('Y-m-d H:i:s');
			$data['status'] = order_status_submission;
			$result = $order_tab->where(['id'=>$orderId])->save($data);
			if(!$result){
				Output::instance()->object([
					'code'=>1,
					'msg'=>'提交失败',
					'results'=>[]
				]);
				return;
			}
			/*更新成功后, 判断供应商如果需要自动同步订单, 那么提交一条任务到任务表中, 确认一次提交的订单是否在同一商城中?*/
			$vendorInfo = $vendorModel->where(['id'=>$orderInfo['vId']])->getField('isSynchro');
			if($vendorInfo['isSynchro']){
				$arr = [];
				$arr['oids'] = $orderId;
				$bool = R('TaskQueue/addTaskQueue', [$name='synchroOrderToCrm', $module='order',
					$interfaceName='ApplePieAction/synchroOrder',$param=json_encode($arr),
					$execute_plan_time=date('Y-m-d H:i:s'), $flag=true,$isCycleExecute=0, $cycleTime=0, $cId = $cid]);
				if(!$bool){
					Log::write('保存同步订单任务失败');
				}
			}

			$templatemsg = $TemplateModel->where(['status'=>order_status_delivering])->find();
			/*您填写的信息已提交成功，我们将尽快确认*/
			$first = '您填写的信息已提交成功，我们将尽快确认。';
			self::sendVendorNotice($orderInfo["vId"],$orderInfo['serialNumber'],$orderInfo['updateTime'],$orderInfo['price']);
			$temData['first'] = array('value'=> $first,'color'=>"#743A3A");
			$temData['keyword1'] = array('value'=>$data['serialNumber'],'color'=>'#173177');
			$temData['keyword2'] = array('value'=> $orderInfo['createTime'],'color'=>'#173177');
			$temData['keyword3'] = array('value'=> '0.00','color'=>'#173177');
			$temData['remark'] = array('value'=> '点击查看订单详情',"color"=>'#008000');
			$toUser = $orderInfo['userName'];
			$template_id = $templatemsg['templateId'];
			$url = C("SERVER_HOST") . "call.html?customerId=" . $cid .
				"&module=product&method=getOrderDetail&params=%7B%22id%22:".$orderInfo['id']."%7D";
			$url = urlencode($url);
			$topcolor = "#FF0000";
			WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$temData);
			//Log::write('jie---form'.$toUser.'|tepId|'.$template_id.'|data|'.print_r($data, true));
			$param = new stdClass();
			$param->id = $orderInfo['id'];
			self::SendQuanOrderNotice($param);
			Output::instance()->object([
				'code'=>0,
				'msg'=>'提交成功',
				'results'=>[]
			]);
            //20180723mh增加短信发送
            if ($orderInfo['userPhone']) {
                $params = new stdClass();
                $params->phone = $orderInfo['userPhone'];
                $params->module = 'nmpOrder' ;
                $params->status = 'form';
                $params->message = '您填写的信息已提交成功,我们将尽快确认';
                Module::callModule('phone', NULL, 'sendSms', $params);
            }
            return;
		}
		//需要支付
		if($payPrice['type'] == 1 && $orderInfo['price'] == 0){
			//需要支付但金额为0
			$data['serialNumber'] = $data['tempSerialNumber'] = self::createOrderSerialNumber($orderId, $cid);
			$data['updateTime'] = date('Y-m-d H:i:s');
			$data['status'] = 'delivering';
			$result = $order_tab->where(['id'=>$orderId])->save($data);
			if(!$result){
				Output::instance()->object([
					'code'=>1,
					'msg'=>'提交失败',
					'results'=>[]
				]);
				return;
			}
		}

		if($payPrice['payPrice'] !== $orderInfo['fixedPrice']){
			Output::instance()->object([
				'code'=>1,
				'msg'=>'商品价格存在变动,请重新填写提交',
				'results'=>[]
			]);
			return;
		}
		if($payType != ORDER_PAYTYPE_WXPAY && $payType != ORDER_PAYTYPE_TENPAY && $payType != ORDER_PAYTYPE_ALIPAY
			&& $payType != ORDER_PAYTYPE_UPAY){
			Output::instance()->object([
				'code'=>1,
				'msg'=>'支付方式不存在',
				'results'=>[]
			]);
			return;
		}
		//Log::write('jie----pay-'.$payType);
		self::submitOrder($orderId, $sid='', $orderInfo['price'], $remark='', $orderInfo['fullName'], $orderInfo['phone'],
			$orderInfo['province'],$orderInfo['city'], $orderInfo['country'],$orderInfo['address'], $orderInfo['orderTime'],
			$storeResourceId='', $storeResourceName='', $orderInfo['type'], $payType, $orderInfo['deliveryType'], $userName);
	}

	/**
	 * 表单订单详情
	 * @param $params
	 */
	public function formOrderDetail($params){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$orderId = $params->orderId;
		$cid = Session::$user['customerId'];
		$uId = Session::$user['userId'];
		Session::switchCustomer(0);
		$order_tab = M('module_product_order');
		Session::switchCustomer($cid);
		$user_tab = M('user');

		//是否关注
		$userInfo = $user_tab->where(['id'=>$uId])->field('id, status')->find();
		if ((empty($userInfo['status']) || in_array($userInfo['status'], ['sharesubscribe', 'unsubscribe']))) {    // 未关注( => 已关注[subscribe|scansubscribe])
			Output::instance()->object([
				'code'      => 1,
				'status'    => 'error',
				'message'   => '请先关注',
				'submessage'=> ''   // 关注的二维码图片
			]);
			return;
		}

		$orderInfo = $order_tab->alias('a')
			->join('wx_'.$cid.'_user_weixin_info b on a.uId=b.userId')
			->join('inner join wx_module_product_order_detail c on a.id=c.oid')
			->where(['id'=>$orderId, 'deleted'=>0])
			->field('a.serialNumber,a.qId,a.uId,a.fullNamea,a.phone,a.address,a.price,a.status,a.payType,
			a.createTime,b.saleCut,b.isMiUserCut,b.name as formName, b.contentId, b.fixedPrice,b.customizedInfo')
			->find();
		if($orderInfo == null){
			Output::instance()->object([
				'code'=>1,
				'msg'=>'订单错误',
				'results'=>[]
			]);
			return;
		}
		switch($orderInfo['status']){
			case ORDER_STATUS_PAYING:
				$orderInfo['statusVal'] = '待支付';
				break;
			case order_status_refund:
				$orderInfo['statusVal'] = '已退款';
				break;
			case ORDER_STATUS_REFUNDEDPART:
				$orderInfo['statusVal'] = '部分退款';
				break;
			case order_status_delivering:
				$orderInfo['statusVal'] = '已付款';
				break;
			case order_status_ok:
				$orderInfo['statusVal'] = '已确认';
				break;
			case order_status_cancel:
				$orderInfo['statusVal'] = '已取消';
				break;
			case order_status_submission:
				$orderInfo['statusVal'] = '已提交';
				break;
			case ORDER_STATUS_CLOSED:
				$orderInfo['statusVal'] = '已关闭';
				break;
			default:
				break;
		}
		Output::instance()->module('product', 'formOrderDetail')->object([
			'code'=>0,
			'msg'=>'ok',
			'results'=>$orderInfo
		]);
	}

}
